本文主要介绍 Spring Boot 中如何使用 Sping Data JPA,相关的环境及软件信息如下:Spring Boot 2.6.10。
1、Sping Data JPA 简介
Spring Data JPA 是 Spring Data 家族的一部分,它对基于 JPA 的数据访问提供了增强支持,让 JPA 更加易用。 它使得使用 Spring 构建的应用程序访问数据库变得更加容易。
编写应用程序的数据访问层是一件很麻烦的事, 必须编写太多样板代码来执行简单的查询以及分页和审计。 Spring Data JPA 旨在通过减工作量来显着改进数据访问层的实现。 作为开发人员,编写数据访问层接口,包括自定义查询方法,Spring 将自动提供实现。
1.1、Spring Data JPA 的特点
- Sophisticated support to build repositories based on Spring and JPA
- Support forQuerydsl predicates and thus type-safe JPA queries
- Transparent auditing of domain class
- Pagination support, dynamic query execution, ability to integrate custom data access code
- Validation of
@Query
annotated queries at bootstrap time - Support for XML based entity mapping
- JavaConfig based repository configuration by introducing
@EnableJpaRepositories
.
1.2、Spring Data JPA 与 Hibernate 的关系
Spring Data JPA 是 Spring 提供的一套对 JPA 操作更加高级的封装,底层依赖 Hibernate 的 JPA 实现。
2、JpaRepository 和 JpaSpecificationExecutor 接口
Spring Data JPA 提供了 JpaRepository 和 JpaSpecificationExecutor 接口,通过它们可以快速定义 DAO 接口,Spring Data JPA 会自动实现该接口。
2.1、JpaRepository
JpaRepository 接口内置了很多方法:
如果不满足业务需求,可以自定义方法。
2.1.1、使用 Query 注解
org.springframework.data.jpa.repository.Query 注解可以定义使用 JPQL 或 SQL 操作数据。
2.1.1、按照 Spring Data JPA 规范定义方法名称
Spring Data JPA 提供一些关键词,通过这些关键词和实体属性名称来组装方法名称。
主题关键词:
Keyword | Description |
| General query method returning typically the repository type, a |
| Exists projection, returning typically a |
| Count projection returning a numeric result. |
| Delete query method returning either no result ( |
| Limit the query results to the first |
| Use a distinct query to return only unique results. Consult the store-specific documentation whether that feature is supported. This keyword can occur in any place of the subject between |
Logical keyword | Keyword expressions |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
详细说明可参考官网文档:https://docs.spring.io/spring-data/jpa/docs/2.6.6/reference/html/#repository-query-keywords。
命名样例:
方法名 | JPQL |
findByLastnameAndFirstname | … where x.lastname = ?1 and x.firstname = ?2 |
findByLastnameOrFirstname | … where x.lastname = ?1 or x.firstname = ?2 |
findByStartDateBetween | … where x.startDate between ?1 and ?2 |
findByAgeLessThan | … where x.age < ?1 |
findByAgeLessThanEqual | … where x.age ⇐ ?1 |
2.2、JpaSpecificationExecutor
JpaSpecificationExecutor 接口主要用来在 JpaRepository 接口无法满足要求时,可以使用 JPA 的标准 API 来操作数据。
3、Sping Data JPA 使用
这里演示下 Spring Data JPA 的基本使用,工程目录结构如下:
3.1、引入依赖
3.2、创建实体类
3.3、编写配置文件(application.yml)
3.4、定义 DAO 接口
3.5、编写启动类
3.6、编写测试用例
3.6.1、增加数据
3.6.2、修改数据
3.6.3、查询数据
3.6.4、删除数据
3.6.5、完整代码
TestService.java