Detailed Explanation of Configuration Method Using Spring data jpa in Spring Boot

  • 2021-07-03 00:13:22
  • OfStack

To solve these many boring data manipulation statements, our first thought is to use the ORM framework, such as hibernate. After integrating Hibernate, we eventually map data changes to database tables by manipulating Java entities.

In order to solve the basic "add, delete, modify and check" operation of abstracting each Java entity, we usually encapsulate a template Dao in a generic way for abstraction and simplification, but this is still not very convenient. We need to write an interface inherited from the generic template Dao for each entity, and then write the implementation of this interface. Although a few basic data accesses are already well reused, there is a heap of Dao interfaces and implementations for each entity in the code structure.

Due to the implementation of template Dao, the Dao layer of these specific entities has become very "thin", and the Dao implementation of some specific entities may be a simple proxy for template Dao, and often such implementation classes may appear on many entities. The emergence of spring-data-jpa can make such an already "thin" data access layer become just a way to write a layer 1 interface. For example, the following example:


public interface UserRepository extends JpaRepository<User, Long> {
  User findByName(String name);
  @Query("from User u where u.name=:name")
  User findUser(@Param("name") String name);
}

We only need to write a file that inherits from JpaRepository The interface can complete data access. Let's take a concrete example to experience the powerful functions brought by Spring-data-jpa.

Use sample

Because Spring-data-jpa depends on Hibernate. If you have a certain knowledge of Hibernate, you can easily understand the following and use Spring-data-jpa. If you are still new to Hibernate, you can get started in the following ways, and then suggest going back to Hibernate to help you understand this part and use it further.

Engineering configuration

In pom.xml Add related dependencies in, and add the following:


<dependency 
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

In application.xml Configuration in: Database connection information (not required if using an embedded database), settings for automatically creating table structure, such as using MySQL as follows:


spring.datasource.url=jdbc:mysql://localhost:3306/test 
spring.datasource.username=root 
spring.datasource.password=root 
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.hbm2ddl.auto=create-drop 

spring.jpa.properties.hibernate.hbm2ddl.auto Is a configuration attribute of hibernate, and its main function is to automatically create, update and verify the database table structure. Several configurations of this parameter are as follows:

create Every time you load hibernate, you will delete the last generated table, and then generate a new table again according to your model class, even if there is no change twice, this is an important reason for the data loss of database tables. create-drop A table is generated from the model class each time hibernate is loaded, but the table is automatically deleted when sessionFactory1 is turned off. update : The most commonly used attributes, the first load hibernate according to model class will automatically establish the structure of the table (the premise is to establish a good database first), after loading hibernate according to model class automatically update the table structure, even if the table structure changes, but the rows in the table still exist and will not delete the previous rows. Note that when deployed to the server, the table structure will not be established immediately, but will not be established until the application is run for the first time. validate Each time hibernate is loaded, validation creates a database table structure that compares with the tables in the database, does not create a new table, but inserts new values.

So far, the basic configuration has been completed. If you have integrated it under Spring, I believe you have already felt the convenience of Spring Boot: The traditional configuration of JPA is in persistence.xml In the file, but we don't need it here. Of course, it is best to organize the project according to the engineering structure of the best practices mentioned above when building the project, so as to ensure that various configurations can be scanned by the framework.

Create Entity

Create an User entity containing id (primary key), name (name), age (age) attributes, which will be mapped to the database table through the ORM framework, due to the configuration hibernate.hbm2ddl.auto When the application starts, the framework will automatically go to the database to create the corresponding table.


@Entity
public class User {
  @Id
  @GeneratedValue
  private Long id;
  @Column(nullable = false)
  private String name;
  @Column(nullable = false)
  private Integer age;
  //  Omit constructor 
  //  Omission getter And setter
}

Create a data provider

The following creates the corresponding for the User entity pom.xml0 Interface implements data access to the entity, as follows:


public interface UserRepository extends JpaRepository<User, Long> {
  User findByName(String name);
  User findByNameAndAge(String name, Integer age);
  @Query("from User u where u.name=:name")
  User findUser(@Param("name") String name);
}

In Spring-data-jpa, you only need to write an interface like the above for data access. We no longer need to write our own interface implementation classes when we write interfaces in the past, which directly reduces our file list.

From the bottom to the top UserRepository For some explanation, this interface inherits from JpaRepository By viewing the JpaRepository Interface API document, you can see that the interface itself has achieved the creation (save), update (save), delete (delete), query (findAll, findOne) and other basic operations of the functions, so the data access for these basic operations do not need to be defined by developers themselves.

In our actual development, JpaRepository Often the interface defined by the interface is not enough or the performance is not optimized enough, so we need to go one step further to implement more complex queries or operations. Since this article focuses on integrating spring-data-jpa in spring boot, we will briefly introduce the exciting functions in spring-data-jpa, and then talk about the common uses in spring-data-jpa separately.

In the above example, we can see the following two functions:

User findByName(String name)
User findByNameAndAge(String name, Integer age)

They implement querying User entities by name and User entities by name and age, respectively, and we can see that we complete the two conditional query methods without any SQL-like statements here. This is one of the big features of Spring-data-jpa: creating a query by parsing the method name.

Summarize


Related articles: