Bootstrapping Hibernate 5 with Spring
Last Updated :
20 Mar, 2024
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:
Java
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();
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.
Java
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.geeksforgeeks.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
<?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.geeksforgeeks.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.
Java
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.
Similar Reads
Spring Boot Setup with Kotlin Spring Boot is one of the best frameworks available to build full-stack enterprise applications. Initially, Spring was used to build stand-alone applications on the Java Platform supporting easy-to-develop and providing lots of handy features to ease the application development. Why Kotlin is Used?T
5 min read
Spring Boot with H2 Database H2 Database in Spring Boot is an embedded, open-source, and in-memory database. It is a relational database management system written in Java. It is a client/server application. It stores data in memory, not persist the data on disk. Here we will be discussing how can we configure and perform some b
6 min read
Spring @Bean Annotation with Example The @Bean annotation in Spring is a powerful way to define and manage beans in a Spring application. Unlike @Component, which relies on class-level scanning, @Bean explicitly declares beans inside @Configuration classes, offering greater flexibility in object creation. In this article, we will explo
9 min read
Rich Domain Model with Hibernate Rich Domain Model in the context of software development and Hibernate is the model where the business logic is encapsulated directly within the domain objects, rather than being separated into the services or other layers. It can allow the domain model to enforce the business rules and ensure data
4 min read
Loading Initial Data with Spring Boot Loading initial data into a Spring Boot application is a common requirement for seeding the database with predefined data. This data could include reference data, default settings, or simple records to populate the application upon startup. The main concept involves using Spring Boot's data initiali
3 min read