Spring JPA过滤器Query方法中的可选条件

时间:2019-05-11 11:40:07

标签: java spring jpa

我想以很少的标准(假设8)从数据库中过滤掉数据。 下面的查询方法很好地做到了这一点。但是实际上,传递给查询方法的此条件可以为空(这意味着选择查询不应包含该条件)。

我应该如何处理这种情况? 我真的不想用n方法来处理每种情况-这不是一个好方法。

@Query("SELECT NEW api.model.GeneralAnnouncementInfo(" +
        "an.id, an.title, po.price, SUBSTRING(an.description, 1, 100), an.provider, an.creationDate, an.url, l.lessorType, concat(loc.city, ' ', loc.district)) " +
        "FROM Announcement as an " +
        "LEFT JOIN an.priceOffer as po " +
        "LEFT JOIN an.lessor as l " +
        "LEFT JOIN an.location as loc " +
        "LEFT JOIN an.propertyData as pd " +
        "WHERE l.lessorType = (:lessor) " +
        "AND pd.roomNumber = (:rooms) " +
        "AND pd.bathroomNumber = (:baths) " +
        "AND pd.parkingAvailability = (:parking) " +
        "AND pd.isSmokingAllowed = (:smokers) " +
        "AND pd.isPetFriendly = (:pets) " +
        "AND pd.area = (:realPrice) " +
        "AND po.price = (:area) ")
Page<GeneralAnnouncementInfo> getAnnouncementsBySearchCriteria(Pageable pageable, 
                                                               String lessor,
                                                               String rooms,
                                                               String baths,
                                                               String parking,
                                                               String smokers,
                                                               String pets,
                                                               String realPrice,
                                                               String area
);

1 个答案:

答案 0 :(得分:2)

我建议切换到JPA Criteria API。它将为您提供所需的额外灵活性(以及哪种JPQL似乎可以使您的情况发挥最大作用)。您可以以编程方式构建查询而没有任何限制,最好的是编译它们。这意味着没有错别字会生存(这是在JPQL查询中要跟踪的噩梦)。另外,您可能要使用JPA metamodel classes;从而提高查询的健壮性。最后,您的存储库方法将如下所示:

private EntityManager em;

private Page<GeneralAnnouncementInfo> getAnnouncementsBySearchCriteria(QueryParameters qParams) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<SampleEntity> criteria = cb.createQuery(GeneralAnnouncementInfo.class);
    Root<GeneralAnnouncementInfo> root = criteria.from(GeneralAnnouncementInfo.class);

    // Programmatically build query details (conditions, joins, aggregations, translation, etc) 
    // ...
    // ...
    // ...


    return em.createQuery(criteria).getResultList();
}