Configure Hibernate5 with Spring4 using java configuration

To configure Hibernate5 with Spring4 using java configuration Spring Configuration class needs to be created. Also one property file containing information about database username/password , connection string, hibernate settings, etc will be required.

Below is the property file which is used during the configuration.

## jdbc configuration 
driverclass = com.mysql.jdbc.Driver
jdbcurl = jdbc:mysql://localhost/db
username = test
password = test

## hibernate configuration
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = true
hibernate.hbm2ddl = create

 

Configuration Class

@Configuration
@ComponentScan(basePackages = { "in.pm.hibernate.genericdao_example" })
@EnableTransactionManagement
public class AppConfiguration {

}

First create a configuration class and annotate it with following annotations

  • @Configuration : Through this annotation Spring will know that this is the java config class
  • @ComponentScan : Specifies the list of base packages which contains Spring beans and hibernate entities. When the spring container starts it will scan these packages and register the beans by reading annotations
  • @EnableTranscationManagement : This will enable spring’s annotation driven transaction management capability

 

 
    @Value("${driverclass}") 
    private String driverClass;
    
    @Value("${jdbcurl}")
    private String jdbcURL;
    
    @Value("${username}")
    private String userName;
    
    @Value("${password}")
    private String password;
    
    @Value("${hibernate.dialect}")
    private String hibernateDialect;
    
    @Value("${hibernate.show_sql}")
    private String hibernateShowSql;
    
    @Value("${hibernate.hbm2ddl}")
    private String hibernateHbm2ddlAuto;

Add properties and annotate it with appropriate value expression, so that value will be taken from property file and bound to the property

 

    @Bean
    public PropertyPlaceholderConfigurer getPropertyPlaceHolderConfigurer() {
        PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
        ppc.setLocation(new ClassPathResource("application.properties"));
        ppc.setIgnoreUnresolvablePlaceholders(true);
        return ppc;
    }

Create PropertyPlaceHolderConfigurer and provide it with the location of the property file. It will read the properties and populate fields defined in above step

 

    @Bean
    public DataSource getDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(jdbcURL);
        dataSource.setUsername(userName);
        dataSource.setPassword(password);
        return dataSource;
    }

    public Properties getHibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", hibernateDialect);
        properties.put("hibernate.show_sql", hibernateShowSql);
        properties.put("hibernate.hbm2ddl.auto", hibernateHbm2ddlAuto);
        return properties;
    }

    //Create a LocalSessionFactoryBean which will be used to create hibernate SessionFactory
    @Bean
    @Autowired
    public LocalSessionFactoryBean getSessionFactory(DataSource dataSource) {
        LocalSessionFactoryBean sfb = new LocalSessionFactoryBean();
        sfb.setDataSource(dataSource);
        sfb.setPackagesToScan("in.pm.hibernate.genericdao_example.entity");
        sfb.setHibernateProperties(getHibernateProperties());
        return sfb;
    }

Now, create datasource and inject this datasource into the function which is used to create SessionFactory.

Create LocalSessionFactoryBean and set the datasource and hibernate properties. Also set the packages to be scanned for hibernate entities. LocalSessionFactoryBean is a Spring FactoryBean which is used to create Hibernate SessionFactory.

 

    @Bean
    @Autowired
    public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
        HibernateTransactionManager tm = new HibernateTransactionManager();
        tm.setSessionFactory(sessionFactory);
        return tm;
    }

Finally create HibernateTransactionManager and assigned it the sessionFactory which was created in the previous step.

NOTE: Please use LocalSessionFactoryBean and HibernateTransactionManager which is under package “org.springframework.orm.hibernate5”.

 

Complete configuration class looks as below :

package in.pm.hibernate.genericdao_example.app;

import java.util.Properties;

import javax.sql.DataSource;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@ComponentScan(basePackages = { "in.pm.hibernate.genericdao_example" })
@EnableTransactionManagement
public class AppConfiguration {

    
    @Value("${driverclass}") 
    private String driverClass;
    
    @Value("${jdbcurl}")
    private String jdbcURL;
    
    @Value("${username}")
    private String userName;
    
    @Value("${password}")
    private String password;
    
    @Value("${hibernate.dialect}")
    private String hibernateDialect;
    
    @Value("${hibernate.show_sql}")
    private String hibernateShowSql;
    
    @Value("${hibernate.hbm2ddl}")
    private String hibernateHbm2ddlAuto;
    
    @Bean
    public PropertyPlaceholderConfigurer getPropertyPlaceHolderConfigurer() {
        PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
        ppc.setLocation(new ClassPathResource("application.properties"));
        ppc.setIgnoreUnresolvablePlaceholders(true);
        return ppc;
    }

    @Bean
    public DataSource getDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(jdbcURL);
        dataSource.setUsername(userName);
        dataSource.setPassword(password);
        return dataSource;
    }

    public Properties getHibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", hibernateDialect);
        properties.put("hibernate.show_sql", hibernateShowSql);
        properties.put("hibernate.hbm2ddl.auto", hibernateHbm2ddlAuto);
        return properties;
    }

    //Create a LocalSessionFactoryBean which will be used to create hibernate SessionFactory
    @Bean
    @Autowired
    public LocalSessionFactoryBean getSessionFactory(DataSource dataSource) {
        LocalSessionFactoryBean sfb = new LocalSessionFactoryBean();
        sfb.setDataSource(dataSource);
        sfb.setPackagesToScan("in.pm.hibernate.genericdao_example.entity");
        sfb.setHibernateProperties(getHibernateProperties());
        return sfb;
    }

    //NOTE: Use HibernateTransactionManager which is under hibernate5 package only.
    @Bean
    @Autowired
    public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
        HibernateTransactionManager tm = new HibernateTransactionManager();
        tm.setSessionFactory(sessionFactory);
        return tm;
    }

}