Why JPA

JPA is niche, but elegant enough to add, because of the rise of micro-services, service granularity refinement, multi-table union scenarios are gradually reduced, more simple single-table queries, and this is where JPA is good at. Therefore, I will use JPA to operate the database in the actual combat project in the future, of course, Mybatis will be integrated in the following tutorial, after all, the mainstream ┑( ̄  ̄)┍.

Without further ado, let’s get to the point.

Step 1: Add dependencies

First, we need to create a new project. For those of you who don’t know how to read HelloWorld, we will add the following dependencies to pom.xml:

Here we have added the two dependencies circled by the red box, and a lombok dependency that simplifies development. If you need to download lombok in the IDEA environment, open the Settings panel, and restart IDEA as shown in the following figure.

Step 2: Configure the file

Go to your application.properties file and configure it:

The meanings of some parameters have been made clear in my comments and will not be covered here.

Step 3: Add the entity class

This is our simple user Entity class. The @Entity annotation is used to generate a database Table, @TABLE is used to specify the name of the Table, @SequenceGenerator is a rule for producing index tables (SEq_USER) with primary keys, @GeneratedValue is used to generate primary keys according to the rule, At sign Id means this is a primary key.

Step 4: Write a simple test program

The Repository:

Yes, you read correctly, this is my operation database interface, but why nothing 🤔, don’t panic, let’s take a look at the inherited interface to provide us with what methods:

As you can see, most of the methods we will use are provided, so what if none of these methods we want and we need to write them ourselves? The syntax in the following table basically helps us to do this:

If this does not satisfy our requirements, we can also write our own statements similar to HQL to query:

ψ(‘ ∇´)ψ will be explained in a separate chapter on the syntax of HQL.

Service:

Interface classes are no longer posted, taking up space.

Controller:

After running the program, you can see that the user table and user index table have been created for us.

To access the address, you can see:

All will be just as we expected. ◕ ‿ ‿ ◕.) づ

Step 5: Add paging

Some of you may have noticed that I inherited this interface to achieve custom sorting and paging functions, so how to use it?

One line of code to solve paging ~ (we probably won’t use this in practice, but this is just a demonstration of how powerful JPA is)

Original article, writing is limited, talent and learning shallow, if the article is not straight, hope to inform.

The source code can be downloaded from Github or the code cloud. The following examples will be updated synchronously.


The public,