使用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);
cafeblue 回答:使用Spring JPA编写动态查询的方法

Spring Data JPA提供了specifications的便捷使用,非常适合过滤。

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

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,cb) -> grp.<Long>get("co_id").in(companyIds);
}

然后结合规格:

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

最后读取数据:

List<Grp> grps = grpRepository.findAll(spec);
本文链接:https://www.f2er.com/3153443.html

大家都在问