Step-by-Step Implementation of Bootstrapping Hibernate 5 with Spring
Below are the steps to implement Hibernate 5 with Spring Application.
Step 1: Add Maven Dependencies
The hibernate-core jar file has to be added to the project class path before we can investigate the new bootstrapping procedure. We only need to define this dependence in the pom.xml file of a Maven-based project.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.4.25.Final</version>
</dependency>
Step 2: Use Tomcat JDBC Connection Pooling
Instead of using Spring’s DriverManagerDataSource, we will utilize Tomcat JDBC Connection Pooling, which is more appropriate for production use.
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-dbcp</artifactId>
<version>9.1.90</version>
</dependency>
Step 3: Create HibernateConfig Class
We need to specify beans for PlatformTransactionManager, DataSource, LocalSessionFactoryBean, and a few Hibernate-specific attributes in order to use Hibernate 5 with Spring.
To set up Hibernate 5 with Spring, let’s develop our HibernateConfig class.
import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Bean;
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 javax.sql.DataSource;
import java.util.Properties;
@Configuration
@EnableTransactionManagement
public class HibernateConf {
// configuring the Hibernate SessionFactory bean
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource()); // setting the data source
sessionFactory.setPackagesToScan("com.w3wiki.hibernate.bootstrap.model"); // Package to scan for entity classes
sessionFactory.setHibernateProperties(hibernateProperties()); // setting Hibernate properties
return sessionFactory;
}
// configuring the data source bean
@Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUrl("jdbc:h2:mem:db;DB_CLOSE_DELAY=-1");
dataSource.setUsername("admin");
dataSource.setPassword("admin");
return dataSource;
}
// configuring the Hibernate Transaction Manager bean
@Bean
public PlatformTransactionManager hibernateTransactionManager()
{
HibernateTransactionManager transactionManager = new HibernateTransactionManager()
{
@Override
protected void doBegin(Object transaction, SessionFactory sessionFactory) throws HibernateException
{
super.doBegin(transaction, sessionFactory);
}
};
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
// configuring Hibernate properties
private Properties hibernateProperties()
{
Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", "create-drop"); // database schema generation strategy
hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); // H2 database dialect
return hibernateProperties;
}
}
Step 4: Use XML configuration
Hibernate 5 may also be configured using an XML-based setup as a backup option:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.w3wiki.hibernate.bootstrap.model"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">create-drop</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="org.apache.tomcat.dbcp.dbcp2.BasicDataSource">
<property name="driverClassName" value="org.h2.Driver"/>
<property name="url" value="jdbc:h2:mem:db;DB_CLOSE_DELAY=-1"/>
<property name="username" value="admin"/>
<property name="password" value="admin"/>
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
</beans>
Step 5: Inject the Hibernate SessionFactory
Hibernate 5 is now all set up with Spring, and anytime we need to, we can just inject the raw Hibernate SessionFactory.
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
// this is marked as a repository to indicate that it is a Spring bean responsible for data access
@Repository
public abstract class BarHibernateDAO {
// Autowired annotation injects the SessionFactory bean into this field
@Autowired
private SessionFactory sessionFactory;
// other methods or properties related to BarHibernateDAO can be added here
}
- @Autowired Annotation: Automatic dependency injection makes use of this annotation.
- @Repository Annotation: This annotation serves as a visual code that the class is a Spring bean with data access responsibility.
- Depending on needs, we can add more methods or properties to the BarHibernateDAO class.
Bootstrapping Hibernate 5 with Spring
Hibernate 5 is a framework used for mapping object-oriented domain models to relational databases for web applications and is provided by the open-source object-relational mapping (ORM) tool. We provide all of the database information in the hibernate.cfg.xml file within the hibernate framework. The hibernation.cfg.xml file is not required if we plan to combine the hibernate application with Spring. All of the data in the applicationContext.xml file is available.
Example of Bootstrapping Hibernate 5 with Spring:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
// creating a Hibernate configuration
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
// creating a SessionFactory object
SessionFactory factory = cfg.buildSessionFactory();
// opening a session
Session session = factory.openSession();
// starting a transaction
Transaction transaction = session.beginTransaction();
// creating and persisting an Employee object
Employee e1 = new Employee(222, "aritrik", 50000);
session.persist(e1); // Persisting the object to the database
// committing the transaction
transaction.commit(); // Transaction is committed
// closing the session
session.close();