gpt4 book ai didi

java - 如何使用分页和排序存储库进行多个参数搜索?

转载 作者:太空宇宙 更新时间:2023-11-04 12:43:20 25 4
gpt4 key购买 nike

我在我的 Spring 项目中使用 jquery 数据表的分页和排序存储库。我尝试使用三个参数进行搜索,例如

@Query(value = "Select p from ProfileBaseInfo p where p.fullName = :fullName or p.firstName = :firstName or p.lastName = :lastName") 
Page<ProfileBaseInfo> search(@Param("fullName") String fullName,@Param("firstName") String firstName,@Param("lastName") String lastName,Pageable pageable);

现在我需要使用不同的组合(即和/或)另外搜索 5 个参数。我根据搜索的参数生成了一个动态查询。 (即)如果存在参数,我将连接表并插入 where 条件。如何将动态生成的查询放入 @Query 中,或者我应该以不同的方式处理这个问题?现在我想要的是我必须建立一个标准,例如 “SELECT * FROM profile where name=? and fullName=? and title=? and city=? and state=? and Country=?”在***@Query***注解中。

我想知道是否还有其他方法可以做到,因为表中的列数可能会很多。

最佳答案

我认为您应该创建一个 Spring bean 来实现您的搜索方法( Spring Data )。@Autowire一些与数据库(EntityManager或类似)对话的bean并写下您需要的任何查询。

我建议您对所有参数使用某种包装对象,例如

class Parameters {
String firstName,
String fullName;
...
Object paramN;

<<getters-setters ?>>
}

并使用CriteriaQuery根据参数构造查询,例如

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<ProfileBaseInfo> cq = cb.createQuery(ProfileBaseInfo.class);
Root<ProfileBaseInfo> from = cq.from(ProfileBaseInfo.class);
...
List<Predicate> predicates = Lists.newArrayList();
...
if (param.getFullName() != null) {
predicates.add(cb.like(cb.lower(ProfileBaseInfo_.fullName)), param.getFullName().toLowerCase() + "%"))
}
...
cb.and(predicates.toArray(new Predicate[predicates.size()]));

因此您可以根据需要扩展参数列表,而无需使用字符串。

关于java - 如何使用分页和排序存储库进行多个参数搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36598126/

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