Here is sample of such Specification for User:
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)
);
}
or even more customizable implementation:
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")))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…