我使用 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);
}
我想知道是否还有其他方法可以做到,因为表中的列数可能很高。
感谢您的帮助。
编辑(布兰登·奥克利发表评论后澄清问题):此解决方案中的问题在于 @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"));
}
Usage:
userRepository.findAll(Specifications.where(UserSpecifications.containsTextInName("irs")))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)