Hibernate and Spring framework

I introduced to you all basic about Hibernate, so you will know in Hibernate, object implements SessionFactory interface, 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 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 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, it 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.

Final attributes are some of the attributes related to Hibernate. We will use the dialect of MySQL, 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, in the database has the following data:

Hibernate and Spring framework

then when running, the result will be:

Hibernate and Spring framework


Hibernate and Spring framework
Đánh giá bài viết
Chia sẽ bài viết này ...Share on Facebook
Facebook
10Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin

Add Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.