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
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
Spring Boot â Building REST APIs with HATEOAS
In this article, we will explore how to build RESTful APIs using the Spring Boot with HATEOAS (Hypermedia as the Engine of Application State). HATEOAS is the key component of the REST application architecture, where each resource not only provides the data but also includes links to other actions th
5 min read
Spring Boot JPA Native Query with Example
Spring Data JPA or JPA stands for Java Persistence API, so before looking into that, we must know about ORM (Object Relation Mapping). So Object relation mapping is simply the process of persisting any Java object directly into a database table. A native query is a SQL statement that is specific to
7 min read
Hibernate - Bag Mapping
For a multi-national company, usually, selections are happened based on technical questions/aptitude questions. If we refer to a question, each will have a set of a minimum of 4 options i.e each question will have N solutions. So we can represent that by means of "HAS A" relationship i.e. 1 question
4 min read
Hibernate - @Version Annotation with Example
@Version annotation is used to specify the version number for a specific entity. Version Number provided using @Version annotation is used to prevent concurrent modification to an entity. When an entity is being updated, the version number is also incremented. If another transaction tries to update
3 min read
Properties with Spring and Spring Boot
Java-based applications using the Spring framework and its evolution into the Spring Boot and the properties play a crucial role in configuring the various aspects of the application. Properties can allow the developers to externalize the configuration settings from the code. Understanding how to wo
4 min read
Spring Boot - Handle to Hibernate SessionFactory
In Spring Boot applications, we use Hibernate as a JPA provider and it can manage the Hibernate SessionFactory. It is crucial for efficient database interactions. The SessionFactory acts as the factory for the Hibernate Sessions which can be used to perform the database operations. In this article,
6 min read
Hibernate - @Transient Annotation with Example
@Transient annotation in Hibernate is used to mark a property or field in an entity class as transient. This means that the field or property marked as transient should be excluded when the data persists in the database. Wherever an entity is mapped to a database table, by default all the non-transi
4 min read