你考虑过
Specifications
是吗?
使用规范,可以动态生成
WHERE
spring数据查询的一部分。
为了在spring数据jpa查询中使用规范,必须扩展
org.springframework.data.jpa.repository.JpaSpecificationExecutor
接口。因此,您的用户存储库可以如下所示:
public interface UserRepository extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> {
}
你的搜索方法可能是这样的
public List<User> getAllFilterByString(String text) {
if(StringUtils.isEmpty(text))
return userRepository.findAll();
Specification<User> specification =
(root, query, cb) -> {
List<Predicate> predicates = new ArrayList<>();
predicates.add(cb.like(cb.lower(root.get("name")), "%"+text.toLowerCase()+"%"));
//check if the text value can be casted to long.
//if it is possible, then add the check to the query
try {
long longValue = Long.valueOf(text);
predicates.add(cb.equal(root.get("id"), longValue));
}
catch (NumberFormatException e) {
//do nothing, the text is not long
}
//check if the text can be casted to boolean
//if it is possible, then add the check to the query
Boolean value = "true".equalsIgnoreCase(text) ? Boolean.TRUE :
"false".equalsIgnoreCase(text) ? Boolean.FALSE : null;
if(value != null) {
predicates.add(cb.equal(root.get("isActive"), value));
}
return cb.or(predicates.toArray(new Predicate[] {}));
};
return userRepository.findAll(specification);
}
首先我们添加
name LIKE %text%
where表达式的一部分。
接下来,我们检查
text
变量可以强制转换为
long
是的。如果可以,则从字符串中获取长值并将其添加到where查询。
最后我们检查
文本
变量可以转换为布尔值。如果可以,那么我们也将该检查添加到查询中。
例如,如果
文本
变量是
测试1
在哪里
WHERE name LIKE '%test1%;
如果
文本
变量是
对
那么在哪里
WHERE name LIKE '%true%' OR is_active = true;
最后,如果
文本
变量是
德意志北方银行
那么在哪里
WHERE name LIKE '%12%' OR id = 12;
注:
我补充说
cb.lower(root.get("name"))
和
text.toLowerCase()
当我们按名称搜索时,为了使搜索不区分大小写。