1.概览
单表查询在业务开发中占比最大,是所有 CRUD Boy 的入门必备,所有人在 JavaBean 和 SQL 之间乐此不疲。而在我看来,该部分是最枯燥、最没有技术含量的“伪技能”。
1.1. 背景
针对单表查询的 JPA 封装,很多读者反馈很方便也很简单,确实能解决了不少问题:
- 不需要写 SQL,能够快速实现,提升开发效率
- 避免查询条件不当引起的性能问题
但,有眼光锐利的读者提出一个问题:为什么要在 SpringData Repository 之外定义一个新的 Repository,而不是与 Spring Data 集成呢?
这是一个非常好的问题,本次我们就解决与 Spring Data 集成问题。
1.2. 目标
实现 QueryObjectRepository 与 Spring Data Jpa 的集成,无需实现新的 Repository,只需按 spring data 规范完成接口定义,由框架生成的 proxy 实现所有的逻辑。
2. 快速入门
2.1. 环境搭建
2.1.1. 引入 spring-data-jpa
首先,引入 Spring data jpa 相关依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
其次,新建 JpaUser Entity 类:
@Data
@Entity
@Table(name = "t_user")
public class JpaUser implements User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Integer status;
private Date birthAt;
private String mobile;
}
新建 JpaUserRepository
public interface JpaUserRepository extends Repository<JpaUser, Long>, JpaSpecificationExecutor<JpaUser> {
}
JpaUserRepository 继承两个接口:
- Repository,标记为一个仓库,由 spring data 为其创建代理类;
- JpaSpecificationExecutor,使其具备 Specification 查询能力;
2.1.2. 引入 singlequery
在 pom 中增加 singlequery 相关依赖:
<dependency>
<groupId>com.geekhalo.lego</groupId>
<artifactId>lego-starter-singlequery</artifactId>
<version>0.1.7-query-SNAPSHOT</version>
</dependency>
Starter 中的
JpaBasedSingleQueryConfiguration 将为我们完成全部配置。
2.2. 【旧】自定义 QueryObjectRepository 方案
接触过旧版本的读者,可以跳过,直接看下一章“spring data jpa 集成”
2.2.1. 定义 Repository
创建 JpaUserSingleQueryService,继承自
BaseSpecificationQueryObjectRepository,具体如下:
@Repository
public class JpaUserSingleQueryService
extends BaseSpecificationQueryObjectRepository
implements UserSingleQueryService {
public JpaUserSingleQueryService(JpaUserRepository specificationExecutor) {
super(specificationExecutor, JpaUser.class);
}
}
其中,构造参数 JpaUserRepository 为 spring data jpa 为我们生成的 Proxy;
BaseSpecificationQueryObjectRepository 为我们提供基本的查询能力;
2.2.2. 创建查询对象,添加查询注解
定义查询对象,具体如下:
@Data
public c