Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

Spring Hibernate Configuration

Hibernate is an ORM based framework that is used to map Java objects to a relational database in Java application. It mainly used to store data in a database. Hibernate is primarily designed to manage databases by using Java code. It maps Java classes to database tables and Java types to database types. It is designed and developed by Red Hat and initially released on 23 May 2001.

We can understand by seeing the following image that shows how the hibernate framework maps java class fields to table columns and their types.

In this tutorial, we will see to configure the hibernate in the spring web application. We can configure hibernate either by using an XML file or Java annotations. The XML approach is older and annotation is a new and modern approach. So we will use annotations to configure the hibernate however you are free to use any approach.

hibernate uses SessionFactory class to handle data tables and provides methods to read, save, and fetch data.

Hibernate Configuration using Java Annotations and Code

This file shows a basic hibernate configuration using Java annotations and code in the Spring application.

package com.studytonight;

import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import java.util.Properties;
import javax.sql.DataSource;


@Configuration
@EnableTransactionManagement
@ComponentScan("com.studytonight") 
public class HibernateConf {

	@Bean
	public LocalSessionFactoryBean sessionFactory() {
		LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
		sessionFactory.setDataSource(dataSource());
		sessionFactory.setPackagesToScan("com.studytonight.models");
		sessionFactory.setHibernateProperties(hibernateProperties());
		return sessionFactory;
	}

	@Bean
	public DataSource dataSource() {
		BasicDataSource dataSource = new BasicDataSource();
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		dataSource.setUrl("jdbc:mysql://localhost:3306/springwithdb?useSSL=false");
		dataSource.setUsername("user-name");
		dataSource.setPassword("password");
		return dataSource;
	}

	@Bean
	public PlatformTransactionManager hibernateTransactionManager() {
		HibernateTransactionManager transactionManager
		= new HibernateTransactionManager();
		transactionManager.setSessionFactory(sessionFactory().getObject());
		return transactionManager;
	}

	private final Properties hibernateProperties() {
		Properties hibernateProperties = new Properties();
		hibernateProperties.setProperty("hibernate.show_sql","true");
		return hibernateProperties;
	}
}

Hibernate Configuration using XML Tags

If you want to use an XML file then use this XML code to configure hibernate with Spring application.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="...">
 
    <bean id="sessionFactory" 
      class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" 
          ref="dataSource"/>
        <property name="packagesToScan" 
          value="com.studytonight.models"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">
                    create-drop
                </prop>
                <prop key="hibernate.dialect">
                    org.hibernate.dialect.MySQL5Dialect
                </prop>
            </props>
        </property>
    </bean>
 
    <bean id="dataSource" 
      class="org.apache.tomcat.dbcp.dbcp2.BasicDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/db_name?useSSL=false"/>
        <property name="username" value="db_user"/>
        <property name="password" value="db_password"/>
    </bean>
 
    <bean id="txManager" 
      class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
</beans>

After configuration, now we can use it anywhere in the application by adding the following line. We mostly use it with the DAO implementation class.

@Autowired
private SessionFactory sessionFactory;

The session factory is a component of Hibernate that is used to create session objects for the application. However SessionFactory is an interface that provides several methods to deal with sessions.

DataBase Dialects

The following are the dialects of the various databases such as Mysql, Oracle, etc.

DataBase Dialect Name
Microsoft SQL Server 2008 org.hibernate.dialect.SQLServer2008Dialect
MySQL org.hibernate.dialect.MySQLDialect
Oracle org.hibernate.dialect.OracleDialect
PostgreSQL org.hibernate.dialect.PostgreSQLDialect
DB2 org.hibernate.dialect.DB2Dialect

In our next topic, we will learn to use hibernate to connect and save data into the Mysql database.