My blog: Lanling xiaosheng, welcome to browse blog!

In this chapter, we will use The Spring Data JPA to access the database. In this chapter, we will use the Spring Data JPA to access the database.

preface

Sping DATA JPA provides the main functions. The first function is the abstraction of Repository. The second function is to track the basic audit information of entity classes. Spring Date JPA can automatically update the version, createDate, createBy, lastModifiedBy, and lastModifiedDate fields as required.

Add Spring Data JPA library dependencies

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

CrudRepository abstraction and CrudRepository abstraction

Repository is one of the main abstractions of Spring Data. It is the interface of the Spring-data-Commons project. CrudRepository is also the interface of the Spring-data-Commons project. But by extending the Repository interface, CrudRepository defines common methods. Save, query, delete by ID, etc. The following figure,

Three, fast implementation:

  • 1. Define entity classes

import org.springframework.data.annotation.CreatedBy; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedBy; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.util.Date; /** * @entity: indicates an Entity. * @table: When the project is started, the corresponding Table can be created. If there is no @ Id a kick-off meeting for error * @ EntityListeners annotation project: five commonly used field update * / @ Entity @ EntityListeners AuditingEntityListener. Class @ Table (name = "T_singer ") public class Singer {/** * @generatedValue The default generation strategy sequence for the primary key is AUTO */ @id @generatedValue (strategy =) GenerationType.SEQUENCE) @Column(name = "singerId") private Long singerId; @column (name = "fist_name") @notnull (message = "name cannot be empty ") @size (min = 2, Max = 5) private String fistName; @Column(name = "LAST_NAME") private String lastName; @Phone private String phone; @Version @Column(name = "version") private int version; /**Temporal Temporal Temporal format * default: 2020-01-12 14:59:56.941 *TemporalType.DATE: 2020-01-12 *TemporalType.TIME: 15:04:27.188 * TemporalType.TIMESTAMP 2020-01-12 15:05:25.758 */ @createdDate @temporal (TemporalType.DATE) private DATE createDate; @CreatedBy private String createBy; @LastModifiedBy private String lastModifiedBy; @LastModifiedDate private Date lastModifiedDate; . }Copy the code

  • 2. Notes and introduction:

  • @Entity: Identifies this as a JPA Entity for which tables will be created when the project is started
  • @GeneratedValue(strategy = GenerationType.SEQUENCE) The primary key grows automatically. The default value is AUTO
  • @table (name = “t_singer”) : the name of the corresponding Table. The default entity name is lowercase.
  • @ EntityListeners (AuditingEntityListener. Class) :

The 5 fields used to enable automatic updating of entities, respectively

private int version;   
private Date createDate;
private String createBy; 
private String lastModifiedBy;  
private Date lastModifiedDate;Copy the code

Note: To ensure that fields are updated automatically add the @enableJPaAuditingPublic annotation on the main class

@SpringBootApplication @EnableJpaAuditing public class Chapter2Application { public static void main(String[] args) { SpringApplication.run(Chapter2Application.class, args); }}Copy the code

@column (name = “fist_name”) : the corresponding database field, default is the Java field name, can be specified for the database specified field.

Of course, you can also specify the length and type of the field

@version@createdDate @createdby @lastModifiedby @lastModifiedDate: Used to mark five commonly used fields

@Temporal(TemporalType.DATE) : Format of time

  • TemporalType.TIMESTAMP 2020-01-12 14:59:56.941, default mode
  • TemporalType. DATE: 2020-01-12
  • TemporalType. TIME: 15:04:27. 188
  • TemporalType. TIMESTAMP 15:05:25 2020-01-12. 758
  • 3. Configuration of JPA and database

Spring: datasource: username: postgres password: 123456 url: jdbc:postgresql://localhost:5432/test driver-class-name: org.postgresql.Driver jpa: database : postgresql show-sql: #update DDL -auto: Update properties: hibernate: # dialect: I used here is PostgreSQL, of course, you can also use the dialect of mysql and other database: org. Hibernate. The dialect. PostgreSQL9Dialect temp: use_jdbc_metadata_defaults : falseCopy the code

Ddl-auto: operation mode on database tables:

  • Create: Delete and recreate the database regardless of whether there was a database before
  • Update: If there is a change, for example, if I change the name of the database column corresponding to a field, then after starting the project, the database will update the original field, but a new field will be added. This is a reuse configuration
  • 4. Write DAO layer;

CrudRepository implements save, delete, and other methods by default. Here we write a method based on the custom SQL query:

package com.miroservice.chapter2.repository; import com.miroservice.chapter2.pojo.Singer; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import java.util.List; Public interface SingerRepository extends CrudRepository<Singer, Long> {/** * Query * @param fistName * @return */ @query (value = "select * from t_singer where fist_name=:fistName", nativeQuery = true) List<Singer> findByFistName(String fistName); . }Copy the code

Enter the creator and updater of the entity

  • Configure AuditorAware

Implement the AuditorAware interface to obtain the current user name, which can be used to obtain the user name from this class when updating the entity. When the program calls the save method of CrudRepository, it will obtain the current user information from the following method getCurrentAuditor.

Implement the creator and modifier of automatically updating information when saving information.

import java.util.Optional; @Configuration public class AuditorAwareBean implements AuditorAware<String> { @Override public Optional<String> getCurrentAuditor() { return Optional.of("admin"); }}Copy the code

  • 6, write the service layer:

Create SingerServiceImpl component and call singerRepository methods to save, delete, and query singerRepository.

import com.miroservice.chapter2.pojo.Singer; import com.miroservice.chapter2.repository.SingerRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class SingerServiceImpl implements SingerService { @Autowired SingerRepository singerRepository; /** * public List<Singer> findByFistName(String fistName) {** * public List<Singer> findByFistName(String fistName) singerRepository.findByFistName(fistName); } /** * save Singer * @param * @return */ @override public void save(Singer Singer) {singerRepository. Save (Singer); } / delete singer * * * * @ param fistName * @ return * / @ Override public void the delete (id) {singerRepository. DeleteById (id); }}Copy the code

  • 7, write Controller layer: POSTman can implement the query

@RestController
public class SingerController {    
    @Autowired    
    SingerService singerService;  
    
    
    @GetMapping("/get")    
    private HttpResponse get(@RequestParam("fistName") String fistName) {      
        return HttpResponse.ok().setData(singerService.findByFistName(fistName)); 
    }    
    
    @PostMapping("/save")   
    private HttpResponse add(@Valid @RequestBody Singer singer) {   
        singerService.save(singer);       
        return HttpResponse.ok();   
    }    
    
    @GetMapping("/delete/{id}") 
    private HttpResponse delete(@PathVariable Long id) {  
        singerService.delete(id);      
        return HttpResponse.ok();   
    }Copy the code

Four, JpaRepository

In addition to the CrudRepository interface, Spring JAP provides the JpaRepository interface, which provides batch, paging, sorting, and so on. The JpaRepository interface extends CrudRepository. Therefore, the JpaRepository interface provides an implementation of all the functions of the CrudRepository interface. Of course, we can choose to use different interfaces for the complexity of the application. The following figure,

import com.miroservice.chapter2.pojo.Singer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
public interface SingerRepository extends JpaRepository<Singer, Long> { 
    /**   
    *     
    * @param fistName   
    * @return   
    */  
    @Query(value = " select * from t_singer where fist_name=:fistName",
           nativeQuery = true)  
    List<Singer> findByFistName(String fistName)
      ;
}Copy the code

Five, the summary

In the actual development, JPA operation is very convenient for the operation of a single table. Of course, JPA also supports the associated query of multiple tables. But in the iterative process of the project, I will use springBoot+Mybatis for the operation of multiple tables, because Mybatis can customize XML in XML. Query requirements are constantly changing, and XML SQL is actually easier to maintain. A better approach when collecting Mybatis and JPA is selected according to requirements.

This chapter briefly describes how to use JPA in Spring Boot to implement data access operations. For more detailed JPA operations, you can skip this chapter and will continue to be explained in future articles.

That’s it, and you can also check out this blog’s #Spring Boot Getting Started Practice series! #

This article is published by OpenWrite!