为SpringDataJpa集成QueryObject模式

1.概览

单表查询在业务开发中占比最大,是所有 CRUD Boy 的入门必备,所有人在 JavaBean 和 SQL 之间乐此不疲。而在我看来,该部分是最枯燥、最没有技术含量的“伪技能”。

1.1. 背景

针对单表查询的 JPA 封装,很多读者反馈很方便也很简单,确实能解决了不少问题:

  1. 不需要写 SQL,能够快速实现,提升开发效率
  2. 避免查询条件不当引起的性能问题

但,有眼光锐利的读者提出一个问题:为什么要在 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 继承两个接口:

  1. Repository,标记为一个仓库,由 spring data 为其创建代理类;
  2. 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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值