Java sql spring hibernate maven

Hibernate 3 with Spring

announcement - icon

Repeatedly, code that works in dev breaks down in production. Java performance issues are difficult to track down or predict.

Simply put, Digma provides immediate code feedback. As an IDE plugin, it identifies issues with your code as it is currently running in test and prod.

The feedback is available from the minute you are writing it.

Imagine being alerted to any regression or code smell as you’re running and debugging locally. Also, identifying weak spots that need attending to, based on integration testing results.

Of course, Digma is free for developers.

announcement - icon

As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

Get started with Spring Data JPA through the reference Learn Spring Data JPA course:

1. Overview

This article will focus on setting up Hibernate 3 with Spring – we’ll look at how to use both XML and Java configuration to set up Spring with Hibernate 3 and MySQL.

Update: this article is focused on Hibernate 3. If you’re looking for the current version of Hibernate – this is the article focused on it.

2. Java Spring Configuration for Hibernate 3

Setting up Hibernate 3 with Spring and Java config is straightforward:

import java.util.Properties; import javax.sql.DataSource; import org.apache.tomcat.dbcp.dbcp.BasicDataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; import org.springframework.orm.hibernate3.HibernateTransactionManager; import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean; import org.springframework.transaction.annotation.EnableTransactionManagement; import com.google.common.base.Preconditions; @Configuration @EnableTransactionManagement @PropertySource(< "classpath:persistence-mysql.properties" >) @ComponentScan(< "com.baeldung.spring.persistence" >) public class PersistenceConfig < @Autowired private Environment env; @Bean public AnnotationSessionFactoryBean sessionFactory() < AnnotationSessionFactoryBean sessionFactory = new AnnotationSessionFactoryBean(); sessionFactory.setDataSource(restDataSource()); sessionFactory.setPackagesToScan(new String[] < "com.baeldung.spring.persistence.model" >); sessionFactory.setHibernateProperties(hibernateProperties()); return sessionFactory; > @Bean public DataSource restDataSource() < BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); dataSource.setUrl(env.getProperty("jdbc.url")); dataSource.setUsername(env.getProperty("jdbc.user")); dataSource.setPassword(env.getProperty("jdbc.pass")); return dataSource; >@Bean @Autowired public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) < HibernateTransactionManager txManager = new HibernateTransactionManager(); txManager.setSessionFactory(sessionFactory); return txManager; >@Bean public PersistenceExceptionTranslationPostProcessor exceptionTranslation() < return new PersistenceExceptionTranslationPostProcessor(); >Properties hibernateProperties() < return new Properties() < < setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); >>; > >

Compared to the XML Configuration – described next – there is a small difference in the way one bean in the configuration access another. In XML there is no difference between pointing to a bean or pointing to a bean factory capable of creating that bean. Since the Java configuration is type-safe – pointing directly to the bean factory is no longer an option – we need to retrieve the bean from the bean factory manually:

txManager.setSessionFactory(sessionFactory().getObject());

3. XML Spring Configuration for Hibernate 3

Similarly, we can set up Hibernate 3 with XML config as well:

     $ $        Then, this XML file is bootstrapped into the Spring context using a @Configuration class:
@Configuration @EnableTransactionManagement @ImportResource(< "classpath:persistenceConfig.xml" >) public class PersistenceXmlConfig < // >

For both types of configuration, the JDBC and Hibernate specific properties are stored in a properties file:

# jdbc.X jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate_dev?createDatabaseIfNotExist=true jdbc.user=tutorialuser jdbc.pass=tutorialmy5ql # hibernate.X hibernate.dialect=org.hibernate.dialect.MySQL5Dialect hibernate.show_sql=false hibernate.hbm2ddl.auto=create-drop

4. Spring, Hibernate and MySQL

The example above uses MySQL 5 as the underlying database configured with Hibernate – however, Hibernate supports several underlying SQL Databases.

4.1. The Driver

The Driver class name is configured via the jdbc.driverClassName property provided to the DataSource.

In the example above, it is set to com.mysql.jdbc.Driver from the mysql-connector-java dependency we defined in the pom, at the start of the article.

4.2. The Dialect

The Dialect is configured via the hibernate.dialect property provided to the Hibernate SessionFactory.

In the example above, this is set to org.hibernate.dialect.MySQL5Dialect as we are using MySQL 5 as the underlying Database. There are several other dialects supporting MySQL:

  • org.hibernate.dialect.MySQL5InnoDBDialect – for MySQL 5.x with the InnoDB storage engine
  • org.hibernate.dialect.MySQLDialect – for MySQL prior to 5.x
  • org.hibernate.dialect.MySQLInnoDBDialect – for MySQL prior to 5.x with the InnoDB storage engine
  • org.hibernate.dialect.MySQLMyISAMDialect – for all MySQL versions with the ISAM storage engine

Hibernate supports SQL Dialects for every supported Database.

5. Usage

At this point, Hibernate 3 is fully configured with Spring and we can inject the raw Hibernate SessionFactory directly whenever we need to:

public abstract class FooHibernateDAO < @Autowired SessionFactory sessionFactory; . protected Session getCurrentSession()< return sessionFactory.getCurrentSession(); >>

6. Maven

To add the Spring Persistence dependencies to the pom, please see the Spring with Maven example – we’ll need to define both spring-context and spring-orm.

Continuing to Hibernate 3, the Maven dependencies are simple:

 org.hibernate hibernate-core 3.6.10.Final 

Then, to enable Hibernate to use its proxy model, we need javassist as well:

 org.javassist javassist 3.18.2-GA 

We’re going to use MySQL as our DB for this tutorial, so we’ll also need:

 mysql mysql-connector-java 5.1.32 runtime 

And finally, we will not be using the Spring data source implementation – the DriverManagerDataSource; instead, we’ll use a production-ready connection pool solution – Tomcat JDBC Connection Pool:

 org.apache.tomcat tomcat-dbcp 7.0.55 

7. Conclusion

In this example, we configured Hibernate 3 with Spring – both with Java and XML configuration. The implementation of this simple project can be found in the GitHub project – this is a Maven-based project, so it should be easy to import and run as it is.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Читайте также:  Creating form in java
Оцените статью