Hibernate and Spring framework

I introduced to you all basic about Hibernate, so you will know in Hibernate, an object implements the SessionFactory interface, which will hold information related to the database connection, the entity to manipulate the database. It’s better if this object is managed by Spring, when we need it we can get it to use immediately. In this tutorial, I will guide you all on how to use Hibernate in the Spring framework.

First, I will create a Maven as an example:

Hibernate and Spring framework

Spring dependency is as follows:

To work with Hibernate, like JPA, we also need to add the spring-orm dependency:

Hibernate dependency:

In this tutorial, I will use MySQL database so I will also add MySQL Driver dependency as follows:

Project Lombok:

For simplicity, in this example, I only define a table containing student information with two columns:

The entity of table student has the following contents:

For Hibernate, Spring 5 supports only one class to create an object implement SessionFactory interface, that is LocalSessionFactoryBean.

This object allows us to declare information related to the database, the entity so we do not need to have the configuration file for Hibernate anymore.

Here’s the information you need to declare for the LocalSessionFactoryBean object in the Spring container:

In the above declaration, as you can see, we have three properties of the LocalSessionFactoryBean object that need to be declared:

The first attribute is related to the Data Source. The Data Source here we can understand is the management of the connection to the database. We can declare many different types of Data Source as many different organizations implement the javax.sql.DataSource interface.

Here, I declare the DataSource using the DriverManagerDataSource object as follows:

The second attribute we need to declare is the information related to the entity. In this tutorial, I only define one entity, Student.

The final attribute is some of the attributes related to Hibernate. We will use the dialect of MySQL, the MySQLDialect, and will display the SQL that Hibernate uses to execute the database.

So we have finished declaring the SessionFactory interface implementation in the Spring container. Now, just using it: D

My example is as follows:

Currently, the database has the following data:

Hibernate and Spring framework

then when running, the result will be:

Hibernate and Spring framework

Add Comment