“Offer comes, ask friends to take it! I am participating in the 2022 Spring Recruit Punch card campaign. Click here for more details.”

Spring Boot integrates Spring Data JPA

Spring Data

The Spring Data project is designed to simplify building Data access technologies based on the Spring framework, including map-Reduce framework for non-relational databases, relational databases, and access support for cloud Data services.

Spring Data contains several subprojects

Spring Data features: Spring Data provides a unified API to operate on the Data access layer; This specification is mainly implemented by the Spring Data Commons sub-module, which provides a unified standard for accessing Data from both relational and non-relational databases. This standard includes add, delete, change, conditional query, sorting, and paging operations.

Spring Data unified Repository interface:

  • Repository

    : Unified interface
    ,id>
  • RevisionRepository

    > : Based on optimistic locking
    ,id>
  • CrudRepository

    : basic CRUD
    ,id>
  • PagingAndSortingRepository < T, ID extends the Serializable > : basic CRUD and paging

Spring Data provides xxxtemplates for Data access classes, such as RedisTemplate, MongoTemplate, and so on

JPA and Spring Data:

  • Basic functions of JpaRespository
    • Write interface inherits JpaRepository with CRUD and paging capabilities
  • Define the method name that conforms to the specification. As long as the method in the interface conforms to the specification, it has the corresponding function
    • Such as the method name findByLastnameAndFirstname, keyword is And, the corresponding part JPQL conditions for “WHERE x.l astname =? AND x.firstname = ? “
    • The method name findByLastnameOrFirstname, Or keyword, corresponding JPQL
  • @query Customize Query SQL
  • Specifications queries (Spring Data JPA supports Criteria queries for JPA 2.0)

Spring Data JPA implements CRUD

Create a new project spring-boot-JPA and introduce Spring Data JPA

View the dependency diagram for JPA

Configure the default data source

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/test
Copy the code

Create an entity class, Telsa, and configure the mapping

@Data
@Entity // annotated as an entity class
@Table(name = "jpa_tesla") // Set the table name for the entity class
public class Tesla {

    @Id // Set the primary key
    @GeneratedValue(strategy = GenerationType.IDENTITY) // Set the primary key to autoincrement
    private Integer id;
    @Column // The column name is the same as the attribute name by default
    private String name;
    @Column(name = "vehicle_type") // Set the column name
    private String vehicleType;
    @Column
    private String factory;
}
Copy the code

Create the Repository package and create the TeslaRepository interface inheriting JpaRepository, where the first of the generics is the type of the entity class and the second is the type of the primary key

public interface TeslaRepository extends JpaRepository<Tesla.Integer> {}Copy the code

The JpaRepository interface contains basic add, delete, change, and query methods

Configure JPA in YML

jpa:
  hibernate:
    Update or create table
    ddl-auto: create
  The console displays the SQL being executed
  show-sql: true
Copy the code

If the application is started for the first time and the database has no tables, you are advised to use DDl-auto: create to create a response table based on the entity class. If the application is not started for the first time, you are advised to change it to DDl-auto: update.

JpaRepositoriesAutoConfiguration would not start automatically after HibernateJpaAutoConfiguration automatic configuration configuration

HibernateJpaAutoConfiguration enable class JpaProperties in the configuration

Jpa automatic configuration items are in the JpaProperties classStarting the main program automatically creates a table based on the table name, field name, and primary key growth declared in the attributes and annotations of the entity class.

Based on the startup log, you can determine that Spring Boot automatically executes the table construction sentence

Test the CRUD method of TeslaRepository

Create the TeslaRepositoryTest test class, inject the TeslaRepository and add the save method

@SpringBootTest
public class TeslaRepositoryTest {

    @Resource
    private TeslaRepository repository;

    @Test
    public void testSave(a){
        Tesla tesla = new Tesla();
        tesla.setName("Model 3");
        tesla.setVehicleType("Compact Car");
        tesla.setFactory("Shanghai Gigafactory"); repository.save(tesla); }}Copy the code

Execute the testSave method

Added the getById method

@Test
public void testGetById(a){
    Tesla tesla = repository.getById(1);
    System.out.println("The queried data is:" + tesla);
}
Copy the code

Execute the getById method

Add the @Proxy(laxy=false) annotation to the Tesla entity class and start again

The console displays the queried data successfully.

This error occurs based on the implementation of JPA. When the database is accessed, the current session for database access and operation has been closed and released, so the message no session is available.

Add an update method to the test class

@Test
public void update(a){
    Tesla tesla = new Tesla();
    tesla.setId(1);
    tesla.setName("Model 3P");
    tesla.setFactory("The Flamont Gigafactory.");
    tesla.setVehicleType("Four-door sedan");
    repository.save(tesla);
}
Copy the code

Execute update method

Based on the SQL statement executed by the console, JPA first executes the query method to see if it exists, updates it if it does, and creates it if it does not

Add a delete method to the test class

@Test
public void delete(a){
    Tesla tesla = new Tesla();
    tesla.setId(2);
    repository.delete(tesla);
}
Copy the code

Execute delete methodBased on the SQL output from the console, you can determine that the record with ID 1 has been deleted