首页 > 解决方案 > 使用spring jpa编写动态查询的方法

问题描述

目前我正在使用以下查询来实现要求。但是现在,一个新的需求出现了,在这个查询中添加了 7 个新的过滤条件。其中 2 个过滤器需要对表进行额外的连接。所有这些过滤器都是非强制性的,它们可以结合使用。

我的问题是我应该如何解决这个要求。最初,我正在考虑以这样一种方式编写一个查询,即所有过滤器都包含表上的所有连接,但这对性能不友好。我也是 Spring JPA 的新手。所以,如果有人过去满足过这样的要求,请您分享它是如何实现的,或者如果有人对如何实现这一点有建议,请您分享。

@Query(value = "SELECT "
    + "a.GROUP_REF_ID as refId "
    + "count(case when c.STAT_CD in :userStatus then (c.grp_user_id) end) as numberOfUsers, "
    + "count(case when b.STAT_CD in :itemStatus then (b.grp_item_id) end) as numberOfItems  "
    + "from grp a left join grp_item b on a.grp_id=b.grp_id left join grp_user c on a.grp_id=c.grp_id "
    + "where a.stat_cd in :status and a.co_id in :cids "
    + "group by a.GROUP_REF_ID,a.grp_nam,a.GRP_DESC,a.co_id,a.co_nam,a.CRTE_BY, "
    + "a.CRTE_DT,a.UPDT_BY,a.UPDT_DT ", countQuery = "select count(*) from grp where stat_cd in :status and co_id in :cids ", nativeQuery = true)
public Page<Object> findByStatusAndCompanyIdIn(@Param("status") String status, @Param("cids") List<Long> companyIds,
    @Param("userStatus") List<GroupUserStatus> userStatus,
    @Param("itemStatus") List<GroupItemStatus> itemStatus, Pageable pageable);

标签: javaspringspring-bootjpaspring-data-jpa

解决方案


Spring Data JPA 提供了方便的规范使用,非常适合过滤。

定义您的规范,例如(每个过滤器添加一个,根据规范根据需要连接表):

public static Specification<Grp> status(final String status) {
    // EQUAL clause
    return (grp, query, cb) -> cb.equal(grp.<String>get("status"), status);
}

public static Specification<Grp> companyIds(final List<Long> companyIds) {
    // IN clause
    return (grp, query, cb) -> grp.<Long>get("co_id").in(companyIds);
}

然后结合规格:

Specifications<Grp> spec = Specifications.where(status(myStatus))
                                         .and(companyIds(myCompanyIds));

最后读取数据:

List<Grp> grps = grpRepository.findAll(spec);

推荐阅读