When it comes to JPA operational database, some people marvel at its simplicity and power, while others feel that it is not flexible enough and affects actual combat efficiency. So why does JPA make people both love and hate it?

A principle of sharpening knives before war

01. Know JPA

Jpa-java Persistence API, Java Persistence API

In summary, JPA provides a POJO-based persistence model for object-relational mapping

Simplify data persistence code development

Mask differences between different persistence apis for the Java community

And what is Hibernate we often say? It is actually an implementation of JPA

02. Get to know Spring Data

Previously, Spring only implemented ways to support JDBC, JPA, and so on internally. Later, Spring consolidated all the tools for Data manipulation into Spring Data, which provides a relatively consistent spring-based programming model while preserving the underlying storage properties.

Main modules:

Spring Data JPA
Spring Data JDBC
Spring Data Redis
Spring Data MongoDB
Copy the code

03. Learn about Spring Data JPA

Spring Data JPA, which is Spring’s encapsulation of JPA.

Spring Data JPA is designed to significantly improve the operation of the Data access layer by reducing the amount of work needed

As a developer, all you need to do is write your Repository interface and include custom methods that Spring automatically provides

04. Common JPA entity class annotations

With some entity class annotations provided by JPA, we can configure a corresponding table so that JPA can automatically build the table for us when the program is running

Common JPA entity class annotations are as follows:

entity

  • @Entity
  • @MappedSuperclass
  • @Table(name)

@entity and @mappedSuperClass are both annotations that declare an Entity class.

Entity indicates that all attributes defined in the declared Entity class are associated with the corresponding table

@mappedSuperClass indicates that the annotated class is a parent class from which subclasses can extend their attributes

@table (name), indicating that the entity class is associated with a Table in the database

A primary key

  • @Id
  • @GeneratedValue(strategy, generator)
  • @SequenceGenerator(name, sequenceName)

@ID and ** @generatedValue ** are often combined for primary key declarations and specify a primary key generation policy and generator (if not specified, JPA sets the default policy based on the database on which the introduced driver depends).

The @SequenceGenerator annotation indicates that the primary key will be generated as a series number

mapping

  • @Column(name,nullable,length,insertable,updatable)
  • @JoinTable(name) @JoinColumn(name)

Both apply to attributes. @column specifies the field information mapped to an attribute

If there are foreign keys, use the combination of ** @joinTable (name)** **@JoinColumn(name)** to define them

Relationship between

  • @OneToOne @OneToMany
  • @ManyToOne @ManyToMany
  • @OrderBy

The first four annotations are used on an attribute and represent the table’s correspondence to that attribute.

@OrDerby is also used on attributes to represent ** @onetomany and @manytomany **, which is the sorting method of one-to-many or many-to-many fields

05. The Repository is introduced

Add **@EnableJpaRepositories** to enable JPA’s Repository support, and Spring will find the following repository extensions

  • CrudRepository

    provides basic add, delete, modify and query methods
    ,>
  • PagingAndSortingRepository < T, ID > used in paging, sorting method
  • JpaRepository

    is used for methods such as persistence
    ,>

06. Query method

1) Define the query by method name

Query method, default only provides the query all or by ID query method.

You don’t need to write SQL to query complex scenarios, such as query by a certain condition, count the number of records, sort display, multi-condition query, query the first or last item, etc. You just need to define the following format in repository

• the find… By… / read… By… / query… By… / get… By…

• count… By…

•… OrderBy… [Asc / Desc]

• And/Or/IgnoreCase

• Top/First/Distinct

2) paging query

• PagingAndSortingRepository < T, ID >

• Pageable/Sort

• Slice/Page

To implement paging query, you can use PagingAndSortingRepository interface, to match the Pagable/Sort, paging query can be realized

Actual combat Actual combat

Have a general understanding of the principle, next, into today’s actual combat link ~

Mysql database.

01. Introduce dependencies

You only need to introduce the spring-data-JPA and mysql driver as two main dependencies.

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope>  </dependency>Copy the code

02. Configure attributes

Configure database connection information and JPA information respectively

The following illustrates the jPA table creation mechanism, whether to print SQL statements, and whether to format SQL statements to display these three common configuration items

# 1, the database connection information configuration spring. The datasource. Url = JDBC: mysql: / / 127.0.0.1:3306 / test? CharacterEncoding = utf8 spring. The datasource. The username = root spring. The datasource. The password = 123456 # don't have to configure the database driver, Driver-class-name = com.mysql.jdbc.driver #2, jPA configuration #create-drop - Delete table #create - Run the program to create a new table, end the program: #update - A new table will be created when there is no table available. The table will not be empty, but will only be updated. Different complains spring. Jpa. Hibernate. DDL - auto = # print SQL update switch spring. Jpa. Properties. Hibernate. Show_sql = true if # format the SQL spring.jpa.properties.hibernate.format_sql=trueCopy the code

There are four types of JPA table creation mechanisms, which have been indicated in the notes. You can choose different mechanisms according to your actual needs. In general, it is recommended to choose the Update mechanism, which is relatively perfect, and there is no need to be afraid of clearing the table or data every time

03. Create an entity class

According to the annotations of the entity class we introduced in the pre-war preparations, we established the entity class User as follows:

@Entity
@Table(name = "USER")
@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {
    @Id
    @GeneratedValue
    private Long id;
    private String name;
    @Column(updatable = false)
    @CreationTimestamp
    private Date createTime;
    @UpdateTimestamp
    private Date updateTime;
}
Copy the code

Use ** @entity and @table (name=”USER”)** to indicate that the Entity class is associated with the USER Table in the database.

The combination of @ID and @GeneratedValue indicates that the field Id is mapped to the primary key. JPA will configure the corresponding primary key generation policy based on the imported database dependencies.

The createTime attribute uses annotations ** @column (updatable=false) and @creationTimestamp ** to indicate that it cannot be modified, and the default value of the corresponding Column in the table is the time at which the corresponding record was inserted.

The annotation ** @updatetimestamp ** indicates that the updateTime attribute automatically changes to the updateTime of the corresponding row record

4. Create the repository

Create your own UserRepository interface and implement CrudRepository

public interface UserRepository extends CrudRepository<User,Long> {

    List<User> findByNameOrderByCreateTimeDesc(String name);
}
Copy the code

05. Call the repository method

1) Open the JPA Repossitory annotation

Add a comment to the startup class: @EnableJpaRepositories

2) Inject a custom Repository

3) Call specific database operation methods

@SpringBootApplication @Slf4j @EnableJpaRepositories public class SpringBootJpaApplication implements ApplicationRunner { @Autowired private UserRepository userRepository; @override public void run(ApplicationArguments args) throws Exception {User User = user.builder ().name(" ") .createTime(new Date()) .updateTime(new Date()) .build(); userRepository.save(user); log.info("one user added :{}",user); Iterable<User> users = userRepository.findAll(); users.forEach(System.out::println); }Copy the code
  1. Run the project

By running the project, we can see from the printed SQL statement that JPA created for us the User table corresponding to the entity class User and generated the serialized primary key IDS when the service started

Then the database insert operation is performed and a data is successfully inserted

Finally, execute the database query to find a user record that we have added

To recap, our main operation was simply to implement the @crudRepository interface and call its methods directly to manipulate the database

So, simple database operations are implemented

Celebrate for a while, then move on to the next step

We tried to customize a method to query by name and sort by CreateTime descending order:

findByNameOrderByCreateTimeDesc(String name)

After invoking and running the service, the result is as follows:

The printed SQL statement says: query by name, sort by CreateTime descending order

Accordingly, if you want to define other query methods, you can simply define them in a custom Repository by following the method definition rules in section 1. Specific rules can view package org. Springframework. Data. The repository. The query. The various parser, such as PartTree class:

JPA also has special ** @query annotations and JPA Named Queries**. You can customize SQL in methods or XML files to implement more scenarios

To sum up

Compared with Mybatis, we can see how much more convenient JPA is. It can be said to be a true ORM framework, with the following two advantages:

I. Directly through the entity class and table, entity attributes and table fields between the association, automatically build tables for us

II. Do not need to consider the use of what kind of database, and basically do not need to write SQL statements

Greatly emancipated coding working people! Is there any

However, as we have seen, JPA’s ORM encapsulation makes it much less flexible to manipulate databases. For example, if we want to implement multi-table associative query, multi-condition query and so on, it will become more complicated

Therefore, to use JPA in a project, it is important to weigh these features up front against the actual needs of the project

Congratulations, you got a few more skill points:

1. Positioning and functions of JPA and Spring DATA

2. How Spring DATA JPA operates on databases

3. The reason why JPA is loved and hated

Well, that’s it. Learn a little every day and time will see you grow

Spring Boot(five) : re-learning Mybatis

This project code has been uploaded to Github ~ if necessary, please refer to github.com/wangjie0919…

If you need any help or have any questions, please add your personal wechat account: 1272808775 and pull you into the technical communication group

Pay attention to wechat public number – green plum main code, get more technical dry goods ~

Highlights from the past

Spring Boot (3) : Operating database -Spring JDBC

SpringBoot (2) : the first SpringBoot project

SpringBoot (1) : Features overview