Spring Boot 2.6.4 (four) - Data Access (Part C JPA)

"Offer arrives, dig friends to pick up! I am participating in the 2022 Spring Recruitment Check-in Event, click to view the details of the event ."

1. Spring Boot integrates Spring Data JPA

Spring Data

The Spring Data project is to simplify the construction of data access technologies based on the Spring framework, including non-relational database Map-Reduce framework, relational database and access support for cloud data services.

Spring Data contains multiple sub-projects

image.png

Features of Spring Data :
Spring Data provides a unified API to operate on the data access layer; this specification is mainly implemented by the Spring Data Commons submodule, which provides access to data for relational databases and non-relational databases. All are based on the unified standard provided by Spring, which includes addition, deletion, modification and query, conditional query, sorting and paging operations.

Spring Data unified Repository interface :

  • Repository<T,ID extends Serializable>: Unified interface
  • RevisionRepository<T,ID extends Serializable, N extends Number & Comparable<N>>: based on optimistic locking mechanism
  • CrudRepository<T,ID extends Serializable>:基本CRUD
  • PagingAndSortingRepository<T,ID extends Serializable>: Basic CRUD and paging sorting

Spring Data provides template XxxTemplate for data access classes, such as RedisTemplate, MongoTemplate, etc.

JPA Spring Data

  • Basic functions of JpaRespository
    • Write an interface to inherit JpaRepository, with CRUD and paging functions
  • Define a method name that conforms to the specification. As long as the method in the interface conforms to the specification, it has the corresponding function.
    • For example, the method name findByLastnameAndFirstname, the keyword is And, and the corresponding JPQL condition part is both "WHERE x.lastname = ? AND x.firstname = ?"
    • Method name findByLastnameOrFirstname, keyword Or, corresponding JPQL
  • @Query custom query, custom query SQL
  • Specifications query (Spring Data JPA supports JPA 2.0 Criteria query)

image.png

2. Spring Data JPA implements CRUD

Create a new project spring-boot-jpa and introduce Spring Data JPAimage.png

View the dependency graph of jpa

image.png

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
复制代码

Create an entity class Telsa and configure the mapping relationship

@Data
@Entity // 标注为一个实体类
@Table(name = "jpa_tesla") // 设置实体类对应的表名
public class Tesla {

    @Id // 设置主键
    @GeneratedValue(strategy = GenerationType.IDENTITY) // 设置主键为自增主键
    private Integer id;
    @Column // 列名默认与属性名一致
    private String name;
    @Column(name = "vehicle_type") // 设置列名
    private String vehicleType;
    @Column
    private String factory;
}
复制代码

Create a repository package, create a TeslaRepository interface to inherit 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> {

    
}
复制代码

The JpaRepository interface contains the basic addition, deletion, modification and search methodsimage.png

configure jpa in yml

jpa:
  hibernate:
    # 更新或者创建数据表
    ddl-auto: create
  # 控制台显示执行的SQL
  show-sql: true
复制代码

If it is the first time to start the application and there is no table in the database, it is recommended to use ddl-auto: create. The application startup can create a corresponding table according to the entity class. If it is not the first time to start, it is recommended to use ddl-auto: update.

JpaRepositoriesAutoConfiguration will start automatic configuration after HibernateJpaAutoConfiguration is automatically configuredimage.png

HibernateJpaAutoConfiguration enables configuration in class JpaPropertiesimage.png

The jpa automatic configuration items are all started in the JpaProperties class to image.pngstart the main program, and the table will be automatically created according to the attributes of the entity class and the table name, field name and primary key growth method declared in the annotation.

image.pngAccording to the startup log, it can be determined that Spring Boot automatically executes the table creation statement

Testing TeslaRepository's CRUD methods

Create TeslaRepositoryTest test class, inject TeslaRepository and add save method

@SpringBootTest
public class TeslaRepositoryTest {

    @Resource
    private TeslaRepository repository;

    @Test
    public void testSave(){
        Tesla tesla = new Tesla();
        tesla.setName("Model 3");
        tesla.setVehicleType("Compact Car");
        tesla.setFactory("Shanghai Gigafactory");
        repository.save(tesla);
    }
}
复制代码

Execute the testSave method

image.png

Added getById method

@Test
public void testGetById(){
    Tesla tesla = repository.getById(1);
    System.out.println("查询到的数据为:" + tesla);
}
复制代码

Execute the getById method

image.png

At this point, you need to add the @Proxy(laxy=false) annotation to the Tesla entity class and execute it again

image.png

The console successfully displays the queried data.

This error is analyzed based on the implementation of JPA, that is, when the database access is performed, the current access and operation session for the database has been closed and released, so it prompts that no Session is available.

Add an update method to the test class

@Test
public void update(){
    Tesla tesla = new Tesla();
    tesla.setId(1);
    tesla.setName("Model 3P");
    tesla.setFactory("弗拉蒙特超级工厂");
    tesla.setVehicleType("四门轿车");
    repository.save(tesla);
}
复制代码

Execute the update method

image.png

According to the SQL statement executed by the console, JPA first executes the query method to check whether it exists, update it if it exists, and create it if it does not exist.

Add delete method to test class

@Test
public void delete(){
    Tesla tesla = new Tesla();
    tesla.setId(2);
    repository.delete(tesla);
}
复制代码

Execute the delete method. image.pngAccording to the SQL output from the console, it can be determined that the record with the id of 1 has been deleted.

Guess you like

Origin juejin.im/post/7079434370821390367