Basic about Hibernate

Hibernate, as I say in this tutorial, besides implementing the JPA specification, also implements its own framework for connecting and manipulating with database management systems. In this first tutorial about Hibernate, I will go straight to an example of using Hibernate to get database data, then you guys can imagine about the Hibernate and how it works. What is the difference with Hibernate implementations for JPA?

OK, I will first create a Maven project as an example:

Basic about Hibernate

In particular, the Hibernate dependency is as follows:

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

Project Lombok:

In this example, we will define a database containing the information of the class and the students of that class as follows:

The preparation steps are finished, now we start going to the main part.

First, in order to work with clazz and students tables in the database, we will map the tables and columns of these tables to Java object first (ORM).

Next, to work with Hibernate we need to have a configuration file. In this file, we will declare the type of database we will use, the information needed for Hibernate to connect to that database, and the Java objects we mapped from the tables in the database.

As you can see, the database, username, password, and information about Java objects are detailed in the Hibernate configuration file. In addition, we can also declare additional information such as display SQL statement, SQL statement format, … I will talk more about these in the next tutorial about Hibernate.

Normally, we place the Hibernate configuration file in the /src/main/resources/ directory of the project.

Basic about Hibernate

OK, we already have the configuration file, so now how to put those configurations to use in our project?

Hibernate supports us to do that by using the Configuration object to put our configuration into an object that implements the SessionFactory interface.

And now we can use the SessionFactory object in our application.

First, we need to open a session to work with Hibernate by:

To start working, we will open a new Transaction:

For example, to add a new class, we will initialize the new Clazz object,

Add a name to this Clazz object:

And now you can use the Session object to store the Clazz object on the database.

It’s simple, isn’t it? To test whether our Clazz object has been saved to the database yet? You can continue to code:

The entire code is as follows:


Basic about Hibernate

Okay, here comes your initial visualization of how we’re going to work with Hibernate, right? In the next article, I will explain some basic concepts for you to know better.

Basic about Hibernate
Đánh giá bài viết
Chia sẽ bài viết này ...Share on Facebook
4Tweet about this on Twitter
Share on LinkedIn

Add Comment

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