gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 17:48:32 25 4
gpt4 key购买 nike

我想用很少的条件从数据库中过滤掉数据(假设它是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
);

最佳答案

我建议切换到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();
}

关于java - Spring JPA过滤器Query方法中的可选条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56089998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com