Home  >  Article  >  Java  >  How SpringBoot integrates the JPA framework

How SpringBoot integrates the JPA framework

王林
王林forward
2023-05-19 09:52:501867browse

    1. Overview of Spring Boot data access

    Spring Data is an open source framework designed to simplify database access and supports Cloud service, provided by Spring. It is an umbrella project that includes a large number of data access solutions for relational and non-relational databases. It is designed to allow us to quickly and easily use various data access technologies. By default, Spring Boot adopts the method of integrating Spring Data to unify the data access layer. By adding a large number of automatic configurations, introducing various data access templates xxxTemplate and a unified Repository interface, it simplifies the operation of the data access layer.

    Spring Data provides support for multiple types of databases. Spring Boot integrates and manages the databases supported by Spring Data and provides various dependency starters. You can list the commonly used database dependency starters of Spring Boot through a table.

    ##spring- boot starter-data-redisRedis key-value data store with Spring Data starter for Redis and Jedis clients spring-boot-starter-data-neo4jNeo4j graph database and Spring Data Neo4j starterspring-boot-starter-data-mongodbMongoDB and Spring Data MongoDB starter

    2. Introduction to Spring Data JPA

    JPA (Java Persistence API, Java persistence API) is the Java persistence specification officially proposed by Sun. It provides an object/relational mapping for Java developers The tool manages relational data in Java. Its main purpose is to simplify existing persistence development work and integrate ORM (Object Relational Mapping, Object/Relational Mapping) technology. Based on the JPA specification, Spring Data makes full use of its advantages and proposes the Spring Data JPA module to perform persistence operations on ORM relational data.

    Spring Data JPA is a set of JPA application frameworks encapsulated by Spring based on the ORM framework and JPA specifications. It provides common functions such as addition, deletion, modification, and query, allowing developers to implement data operations with less code. It is also easy to expand. Before introducing Spring Boot's integration of JPA, let's briefly introduce the basic use of Spring Data JPA.

    2.1 Write ORM entity class

    The Spring Data JPA framework operates on data with ORM relationships, so when using Spring Data JPA, you first need to write an entity class to map with the data table , and configure the mapping relationship.

    @Entity(name = "t_comment")  // 设置ORM实体类,并指定映射的表名
    public class Discuss {
        @Id   // 表明映射对应的主键id
        @GeneratedValue(strategy = GenerationType.IDENTITY) // 设置主键自增策略
        @Column(name = "article_id")  // 指定映射的表字段名
        private Integer articleId;
        // Generate: Getter and Setter、toString()
    }

    Regarding the above code, Brother Yi will give you a brief explanation of the annotations used.

    Use the annotation @Entity to indicate that the entity class is mapped to the database. At this time, the name of the database table defaults to the first letter of the class name in lowercase. Of course, you can also use the name attribute to specify the mapped table name.

    @ld: Marked on the class attribute or getter method, indicating that a certain attribute corresponds to the primary key in the table.

    The @GeneratedValue annotation can be omitted. It is marked in the same position as the @ld annotation and is used to define the primary key generation strategy corresponding to the attribute. The primary key generation strategies supported by Spring Data JPA include TABLE (using a specific database table to save the primary key), SEQUENCE (a database primary key generation strategy that does not support primary key auto-increment), IDENTITY (primary key auto-increment) and AUTO (JPA independently selects the front 3 suitable strategies, which are the default options).

    When the class attribute and table field name are different, the @Column annotation can be used in conjunction with the name attribute to indicate the table field name corresponding to the class attribute.

    2.2 Write Repository interface

    Write corresponding Repository interfaces for different table data operations, and write corresponding data operation methods as needed.

    public interface DiscussRepository extends JpaRepository<Discuss, Integer> {
        // 1.查询author非空的Discuss评论集合(JPA支持的方法名关键字查询方式)
        List<Discuss> findByAuthorNotNull();
        // 2.根据文章id分页查询Discuss评论集合
        @Query("SELECT c FROM t_comment c WHERE c.articleId = ?1")
        List<Discuss> getDiscussPaged(Integer articleid, Pageable pageable);
        // 3.使用元素SQL语句,根据文章id分页查询Discuss评论集合,nativeQuery为true表示用来编写原生SQL语句 
        @Query(value = "SELECT * FROM t_comment WHERE article_Id = ?1", nativeQuery = true)
        List<Discuss> getDiscussPaged2(Integer articleid, Pageable pageable);
        //4.根据评论id修改评论作者author
        @Transactional // 表示支持事务管理
        @Modifying // 表示支持数据变更
        @Query("UPDATE t_comment c SET c.author = ?1 WHERE c.id = ?2")
        Integer updateDiscuss(String author, Integer id);
        // 5.根据评论id删除评论
        @Transactional
        @Modifying
        @Query("DELETE t_comment c WHERE c.id = ?1")
        Integer deleteDiscuss(Integer id);
    }

    Regarding the special requirements when writing the Repository interface, Brother Yi will explain it to everyone.

    2.2.1 Inherit the XXRepositoryffbe4eed12645b467bc428156552ef14 interface

    When we use Spring Data JPA to customize the Repository interface, we must inherit the XXRepositoryffbe4eed12645b467bc428156552ef14 interface , where T represents the entity class to be operated, and ID represents the primary key data type of the entity class. In the above example, we choose to inherit the JpaRepository interface. The inheritance structure of JpaRepository is shown in the figure below.

    The following describes the interfaces involved in the JpaRepository interface inheritance structure, as follows.

    (1) Repository is the top-level parent interface provided by Spring Data JPA for customizing the Repository interface. No methods are declared in this interface.

    (2) The CrudRepository interface is one of the inherited interfaces of Repository and contains some basic CRUD methods.

    (3) The PagingAndSortingRepository interface inherits the CrudRepository interface and provides two methods of paging and sorting.

    (4) The QueryByExampleExecutor interface is the top-level parent interface for conditional encapsulation queries, allowing complex conditional queries to be executed through Example instances.

    The JpaRepository interface inherits both the PagingAndSortingRepository interface and the QueryByExampleExecutor interface, and provides some additional data operation methods. Usually when writing a custom Repository interface file, we will directly choose to inherit the JpaRepository interface.

    2.2.2 Multiple ways to operate data

    When using Spring Data JPA for data operations, there are many implementation methods, the main methods are as follows.

    (1). If the custom interface inherits the JpaRepository interface, it includes some commonly used CRUD methods by default.

    (2). In the custom Repository interface, you can use the @Query annotation with SQL statements to check, modify, and delete data.

    (3). In the custom Repository interface, you can directly use the method name keyword to perform query operations.

    Among them, the method name keywords supported in Spring Data JPA and the corresponding SQL fragment descriptions are shown in the following table.

    2.2.3 @Transactional Transaction Management

    In the custom Repository interface, data change operations (modification, deletion), regardless of whether the @Query annotation is used, must be in the method Add the @Transactional annotation above for transaction management, otherwise an InvalidDataAccessApiUsageException will occur during program execution. If the @Transactional annotation has been added to the business layer Service class that calls the Repository interface method for transaction management, the @Transactional annotation can be omitted in the Repository interface file.

    2.2.4 @Moditying annotation

    In the custom Repository interface, use the @Query annotation to perform data change operations (modification, deletion). In addition to using the @Query annotation, you must also Add @Moditying annotation to indicate data changes.

    2.3.5 Complex condition query

    JPA also supports using Example instances for complex condition query. For example, query for the existing findAll(Example1eefd63bbe027a2807ccada294a3372c var1) method in the JpaRepository interface.

    3. Use Spring Boot to integrate JPA

    Use Spring Boot to integrate JPA. The specific steps are as follows.

    3.1 Add Spring Data JPA dependency starter

    Add Spring Data JPA dependency starter in the project's pom.xml file.

    Note:

    We have not written the version number corresponding to Spring Data JPA. This is because Spring Boot uniformly manages the version number of Spring Data JPA.

    3.2 Write ORM entity class

    In order to facilitate operation, take the previously created database table t_comment as an example to write the corresponding entity class. Copy the previously created Comment class and rename it to Discuss. At the same time, add JPA corresponding annotations for mapping configuration.

    3.3 Writing the Repository interface

    Create a Repository interface DiscussRepository under the com.cy.repository package for operating the database table t_comment.

    3.4 Write unit tests for interface method testing

    Copy the Chapter03ApplcationTests test class at the current location and rename it to JpaTests to write JPA-related unit tests and slightly modify the content. Write the test method corresponding to the DiscussionRepository interface.

    The test method uses the JpaRepository default method, method name keyword, @Query annotation and Example encapsulated parameters to perform data operations.

    3.5 Integration Test

    Select the unit test method in the JpaTests test class to demonstrate the effect.

    Name Description
    mybatis-spring -boot-starter MyBatis Starter
    mybatis-plus-boot-starter MyBatis-Plus Starter
    spring-boot-starter-data-jpa Spring Data JPA and Hibernate starter

    The above is the detailed content of How SpringBoot integrates the JPA framework. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete