使用spring jpa编写动态查询的java方法
目前我正在使用下面的查询来达到要求。但是现在,一个新的需求出现了,其中有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);
# 1 楼答案
Spring数据JPA提供了specifications的方便使用,它非常适合过滤
定义您的规范,例如(每个过滤器添加一个,根据规范需要连接表):
然后结合规格:
最后阅读数据: