【问题标题】:Approach to write dynamic query using spring jpa [duplicate]使用spring jpa编写动态查询的方法[重复]
【发布时间】:2020-03-02 18:15:09
【问题描述】:

目前我正在使用以下查询来实现要求。但是现在,一个新的需求出现了,在这个查询中添加了 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);

【问题讨论】:

    标签: java spring spring-boot jpa spring-data-jpa


    【解决方案1】:

    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, 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);
    

    【讨论】:

    • 感谢您的回答。我阅读了它,发现我们也可以为此使用 query-dsl。你怎么看。我应该去规范还是查询-dsl。从性能角度来看,这将是一个不错的选择
    • SO 不是发表意见的网站,而是针对具体问题的解决方案。 QueryDSL 也是一个潜在的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2017-05-13
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    • 2017-04-22
    • 1970-01-01
    • 2021-09-18
    • 2015-01-27
    相关资源
    最近更新 更多