我正在使用 Spring Data 进行分页和排序。但是,我想执行多列搜索。
现在,我在我的存储库界面中使用注释 @Query,如下所示:
public interface MyRepository extends PagingAndSortingRepository<Item,Long> {
@Query(value="select mt from MY_TABLE mt where mt.field1 = %searchtext% or mt.field2 = %searchtext% or mt.field3 = %searchtext%")
Page<Item> findByAllColumns(@Param("searchtext") String searchtext, Pageable pageable);
}
我想知道是否有另一种方法可以做到,因为表中的列数可能很高。
感谢您的帮助。
编辑(在 Brandon Oakley 的评论后澄清问题):此解决方案中的问题出在 @Query 注释的 where 子句中,因为我们必须为我们想要的每一列重复完全相同的 searchtext 参数搜索
最佳答案
以下是此类用户规范的示例:
public static Specification<User> containsTextInName(String text) {
if (!text.contains("%")) {
text = "%" + text + "%";
}
String finalText = text;
return (root, query, builder) -> builder.or(
builder.like(root.get("lastname"), finalText),
builder.like(root.get("firstname"), finalText)
);
}
或者更可定制的实现:
public static Specification<User> containsTextInAttributes(String text, List<String> attributes) {
if (!text.contains("%")) {
text = "%" + text + "%";
}
String finalText = text;
return (root, query, builder) -> builder.or(root.getModel().getDeclaredSingularAttributes().stream()
.filter(a -> attributes.contains(a.getName()))
.map(a -> builder.like(root.get(a.getName()), finalText))
.toArray(Predicate[]::new)
);
}
public static Specification<User> containsTextInName(String text) {
return containsTextInAttributes(text, Arrays.asList("lastname", "firstname"));
}
用法:
userRepository.findAll(Specifications.where(UserSpecifications.containsTextInName("irs")))
关于java - Spring Data - 多列搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25872637/