Basic about JPA

In this tutorial, as the tutorial introducing basic about Hibernate, not lengthy, I will go straight to an example of JPA with the implementation of Hibernate to give you a first look and understand how JPA works.

First, I will create a Maven project as follows:

Basic about JPA

Since I’m going to use JPA with Hibernate’s implementation, so I’ll add Hibernate dependencies like this:

I will also 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 of this tutorial.

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, we will create a configuration file to work with JPA.

This configuration file will contain information about one or more persistence units. A persistence unit is a collection of information about which Java objects map to the tables in the database and information about the connection to the database, username, and password. In addition, it contains some other configuration information.

I will explain in detail these configurations in some incoming tutorials.

Normally, we will name this configuration file persistence.xml and this file will be located in the /src/main/resources/META-INF directory of the project.

Basic about JPA

OK, we’re done, so now how to use those configuration information.

We will use the Persistence object of JPA to read that configuration information and use the EntityManagerFactory object to contain them.

Notice that, jpaexample is the name of the persistence unit that we have declared in the configuration file.

And now, we can use the EntityManagerFactory object to work.

To work with JPA, we will get an EntityManager object from the EntityManagerFactory.

If you need an operation related to updating the database, we need to open a new transaction. If not then do not need to open the transaction. Here, I need to add a new class, so I will open a transaction as follows:

Here we will add a new record to the clazz table so we will initialize the new Clazz object:

And use the EntityManager object to save this Clazz object to the database:

The entire code is as follows:


Basic about JPA

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

Add Comment