Spring Data [Introduction to Spring Data, Spring Data JPA, Spring Data JDB] (1)-Comprehensive and detailed explanation (learning summary --- from entry to deepening)

 

Table of contents

1. Introduction to Spring Data

2. Spring Data JPA 

3. Spring Data JDB


1. Introduction to Spring Data

 

Spring Data is a sub-project of Spring, which aims to unify and simplify various types of persistent storage and access. Spring Data uses a set of similar APIs to perform CRUD on relational databases, non-relational databases, search engines and other technologies.

Spring Data provides many modules to support various database operations. Such as Spring Data JPA, Spring Data JDBC, Spring Data Redis, Spring Data MongoDB, Spring Data Elasticsearch, Spring Data Solr, etc. Next, we will explain the usage of these modules respectively.

Note: All projects in this set of courses are built based on the SpringBoot environment, and students need to have a certain understanding of SpringBoot knowledge.

2. Spring Data JPA 

1. Concept

Spring Data JPA is a set of JPA application framework encapsulated by Spring based on the JPA specification. It has more operation methods than JPA.

2. JPA review

JPA is an ORM (Object Relational Mapping) framework provided by JAVA. The ORM frameworks we have learned before include Mybaits and so on. JPA is a set of standardized interfaces, and does not provide implementation, which is implemented by third-party framework providers. The main implementations of JPA include Hibernate, EclipseLink, and OpenJPA. Developers only need to use JPA in the way defined in the specification. No matter which implementation is used, the development method is the same.

The way of JPA to operate the database includes using the method that comes with EntityManage, using JPQL and so on. JPA's multi-table query is different from Mybatis. Mybatis is SQL-oriented for multi-table query, while JPA configures object relationships through annotations such as @OneToMany and @ManyToMany to complete multi-table query.

3. Spring Data JPA project construction

1. Create a SpringBoot project

2. Introduce Spring Data JPA dependency

<dependencies>
   <!-- springData JPA 的起步依赖 -->
   <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
   </dependency>
  <!-- MySQL 连接驱动 -->
   <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
   </dependency>
 <!--jdk9 需要导入如下坐标-->
  <dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.0</version>
  </dependency>
</dependencies>

3. Configuration file configuration Spring Data JPA

spring:
  # 配置数据源
  datasource:
    driverClassName: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql:///数据库名?serverTimezone=GMT%2b8
    username: root
    password: root
    # 配置 spring data jpa
 jpa:
    database: MySQL
    show-sql: true
    generate-ddl: true
    hibernate:
      ddl-auto: update
      naming_strategy: org.hibernate.cfg.ImprovedNamingStrategy
      # 解决属性使用驼峰命名法无法与数据库字段向匹配
      naming:
         physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

4. Create an entity class: the writing method of the entity class is the same as that of JPA.

5. Create a Repository interface, which needs to inherit the following two interfaces:

         JpaRepository: This interface provides basic CRUD operations

        JpaSpecificationExecutor: This interface provides complex query operations

6. Test, common methods of Repository:

         save: add/modify. If the primary key exists, it is modified, otherwise it is added.

         delete: delete

         findOne: query by id 

         findAll: query all

4 Spring Data JPA Principles

 

1. SpringDataJPA generates the proxy object of the interface through the invoke method of the JdkDynamicAopProxy class, and the object is of type SimpleJpaRepository.

2. The SimpleJpaRepository object is an object that actually implements the interface of JpaRepository and JpaSpecificationExecutor, and calls the method of the EntityManage object of JPA when it is implemented.

3. The method of JPA is implemented by Hibernate, and when implemented, Hibernate calls the underlying JDBC to implement database operations.

5 Spring Data JPA query method 

5.1 Use the method query that comes with the JpaRepository interface

count: Query the total number of records

 existsById: check whether the record exists 

getOne/findById: query by id

       findById: load immediately

       getOne: Lazy loading, transaction support @Transcational needs to be added to the test method

 

5.2 Querying with JPQL

Define the method in the Repository interface, add @Query("JPQL") to the method

 JPQL uses the parameter index as a placeholder, and the parameter index starts from 1

 When using JPQL with additions, deletions and modifications, you need to add @Modifying to the interface method

          Note: When testing the JPQL method of addition, deletion and modification, you need to add transaction support @Transactional to the test method, and turn off automatic rollback @Rollback(false)

5.3 Query using native SQL

Define the method in the dao interface, add @Query(value="SQL", nativeQuery=true) to the method 

The remaining usage is the same as JPQL.

5.4 Query according to the rule naming method

Just name the method in the dao interface according to the rules of SpringDataJPA, and the method can complete the query.

 Rule: The query method starts with findBy, and when query conditions are involved, the attributes of the conditions are connected with condition keywords.

 

5.5 Query using the method provided by JpaSpecificationExecutor 

Method: findAll() The meaning of method parameters:

      Specification: query condition object

      Pageable: pagination condition object

      Sort: sorting condition object

5.5.1 Specification

Specification is an interface. By implementing this interface and rewriting the toPredicate method, a query condition object can be constructed.

toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb)

The root object can get the query attribute object Path object

The cb object can construct the Path object as a query condition object  

5.5.2 Pageable

Pageable is an interface. It has an implementation class PageRequest, which contains paging parameters. The PageRequest object can be obtained through the PageRequest.of(pageNum, pageSize) method, and the PageRequest object can be obtained by passing the PageRequest object into the query method as a parameter to obtain the Page object.

5.5.3 Sort

Sort is a class, creating a Sort object can build a sorting condition, and passing the Sort object as a parameter to the query method will sort the results.

6 Domain Driven Design (DDD)

Spring Data JPA is more in line with the domain-driven design (DDD) project design pattern.

We used data-driven design when building the project before. For example, we now have an order class (Order) and an order detail class (OrderItem). There is a one-to-many relationship between orders and order details, that is, one order can buy many products, and each product corresponds to a detail. The design is as follows:

public class Order {
    private Long id;
    private Date orderTime; //下单时间
    // ...省略属性
}
public class OrderItem {
    private Long id;
    private Long productId; // 产品 Id
    // ...省略属性
}

Then we write the OrderDao class and the OrderItemDao class to be responsible for operating the database.

If we add a new order, we need to call the save method of OrderDao and OrderItemDao respectively to save the records of Order and OrderItem in the database table. This is the design for data, always consider what data is stored in the database. But if the business is very complex, data-driven design will face the problem of cumbersome maintenance. Programmers need to understand other Dao codes when operating order data, which is a waste of energy.

The domain-driven model is to design a whole business as a domain, such as new order business. The business requires two types of objects, Order and OrderItem, which we call aggregation. The operations in the aggregation are all done through the aggregation root. We can operate all the objects in the aggregation by operating Order, so Order is the aggregation root in this aggregation. code show as below:

@Entity
@Table(name = "bz_order")
public class Order {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String mobile; //下单手机
    @OneToMany(cascade = CascadeType.PERSIST)
    @JoinColumn(name = "order_id", referencedColumnName = "id")
    private List<OrderItem> orderItemList = new ArrayList();
    // 省略其他属性和 getter/setter
}

@Entity
@Table(name = "bz_orderItem")
public class OrderItem {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Integer id;
        private Long productId; // 产品 Id
        @ManyToOne
        @JoinColumn(name = "order_id",referencedColumnName = "id")
        private Order order;
        // 省略其他属性和 getter/setter
}

 We only need to prepare the Repository class of the aggregate root

public interface OrderRepository extends JpaRepository<Order, Long>, JpaSpecificationExecutor<Order> {}

Use the Repository of the aggregate root to complete the operation of the entire aggregate

Order order = new Order();
order.setMobile("13888888888");
OrderItem orderItem1 = new OrderItem();
OrderItem orderItem2 = new OrderItem();
orderItem1.setProductId(1001L);
orderItem2.setProductId(1002L);
order.getOrderItemList().add(orderItem1);
order.getOrderItemList().add(orderItem2);
orderRepository.save(order);

3. Spring Data JDB

1. Concept

Spring Data JDBC is a submodule of Spring Data, similar to Spring Data JPA, but lighter and simpler. Spring Data JDBC does not provide JPA features such as caching, lazy loading, etc., which makes Spring Data JDBC a simpler, limited, and flexible ORM framework. And Spring Data JDBC supports the integration of Mybatis.

2. Spring Data JDBC project construction 

 2.1. Create a SpringBoot project

 2.2. Introducing Spring Data JDBC dependencies

<dependencies>
   <!-- springData JDBC 的起步依赖 -->
   <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jdbc</artifactId>
   </dependency>
   <!-- MySQL 连接驱动 -->
   <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
   </dependency>
</dependencies>

3. Write the configuration file

spring:
    # 配置数据源
    datasource:
    driverClassName: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql:///数据库名?serverTimezone=GMT%2b8
    username: root
    password: root

4. Create entity classes: Entity classes are written in a similar way to Spring Data JPA, but annotations such as @Entity and @GeneratedValue cannot be used.

5. Create a Repository interface, which needs to inherit the following two interfaces:

        CrudRepository: This interface provides basic CRUD operations

        PagingAndSortingRepository: This interface provides paging sorting queries

6. Test the methods of the Repository interface

3 Spring Data JDBC query method

 3.1 Use the method query of the Repository interface

         Query using methods inherited from interfaces

         Use @Query("sql") to customize the query method

         Query according to the rule naming method

3.2 Query using JdbcTemplate method

JdbcTemplate is a tool class for operating databases provided by Spring after encapsulating the original JDBC. Its usage is as follows:

1. Inject the JdbcTemplate object

2. Call method

        (1) update(sql statement,...parameter of placeholder): Execute DML statement

        (2) queryForObject(sql, new BeanPropertyRowMapper<>(result type.class),...parameters): Execute the DQL statement whose query result is a single row

        (3) queryForObject(sql,resulttype.class,...parameters): Execute the DQL statement whose query result is a single row and single column.

        (4) query(sql,new BeanPropertyRowMapper<>(generic type of the result set.class),...parameter): Execute the DQL statement that the result set is multi-row 

4 Comparison of Repository and Template methods 

When learning Spring Data JDBC, we used two query methods, Repository and Template, and Spring Data JPA also supports the use of JdbcTemplate. In fact, for Spring Data, most modules support these two query methods, so how should we choose?

By directly inheriting the xxxRepository interface, you don't have to write the implementation class yourself, and you can easily implement simple addition, deletion, modification, query, paging, sorting, etc. operations, but for very complex queries, it is more laborious to use.

To use xxxTemplate directly, you need to write SQL statements by yourself, but you can control the addition, deletion, modification and query by yourself. For complex queries, it is more convenient to use.

Generally, for simple operations, directly inherit the Repository interface, and for complex operations, use Template to complete.

5 Comparison between Spring Data JDBC and Spring Data JPA 

Spring Data JDBC is similar to Spring Data JPA, but lighter and simpler. The use of Spring Data JPA must integrate JPA, Hibernates and other frameworks, and Spring Data JDBC can be used directly. Spring Data JDBC does not support JPA functions such as JPQL, caching, and lazy loading, but Spring Data JDBC can be integrated with MyBatis.

6 Spring Data JDBC integration with MyBatis

Spring Data JDBC integrates MyBatis to use Mybatis cache, lazy loading and other functions. The code is as follows:

1. Introduce the mybatis starter dependency:

<!-- mybatis-starter -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.1</version>
</dependency>

 2. Create Spring Data JDBC extension interface

public interface StudentRepositoryExtension {
    List<Student> list();
}

3. mybatis configuration file

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://www.mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.tong.springdata.jdbc.StudentRepositoryExtension">
    <!--查询列表-->
    <select id="list" resultType="com.tong.springdata.jdbc.Student">
        select * from bz_student
    </select>
</mapper>

4. Springboot configuration scan xml

mybatis:
    mapper-locations: classpath:mapper/*Mapper.xml

5. Use mybatis to implement the Spring Data JDBC extension interface, here you can use sqlsession for caching and other operations.

@Repository
public class StudentRepositoryExtensionImpl implements StudentRepositoryExtension {
    @Autowired
    private SqlSession sqlSession;
    @Override
    public List<Student> list() {
        return sqlSession.selectList(StudentRepositoryExtension.class.getName() + ".list");
    }
}

 6. StudentRepository inherits the extended interface

public interface StudentRepository extends CrudRepository<Student, Integer>, PagingAndSortingRepository<Student,Integer>,StudentRepositoryExtension

7. Test

List<Student> list = studentRepository.list();

Guess you like

Origin blog.csdn.net/m0_58719994/article/details/132003971