我为我的地理地图创建了一个CriteriaBuilder
。但是这些条件不是必需的,并且可以获取空值。如果情况不同,我尝试构建不同的搜索语句,但我认为这不是最佳方法。
如果值是null,是否有更好的方式说我的CriteriaBuilder,在搜索时应忽略此值?
过滤器示例:
UserSpecification specName =
new UserSpecification(new SearchCriteria("name", ":", data.getName()));
UserSpecification specEnv =
new UserSpecification(new SearchCriteria("env", ":", data.getEnv()));
...
if(data.getEnv().isEmpty()){
List list = gisMapRepository.findAll(Specification.where(specName));
}
Userspecification.java:
public class UserSpecification implements Specification<GeoMap> {
private SearchCriteria criteria;
public UserSpecification(SearchCriteria criteria) {
this.criteria = criteria;
}
@Override
public Predicate toPredicate
(Root<GeoMap> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
if (criteria.getOperation().equalsIgnoreCase(":")) {
if (root.get(criteria.getKey()).getJavaType() == String.class) {
return builder.like(
root.<String>get(criteria.getKey()), "%" + criteria.getValue() + "%");
} else {
return builder.equal(root.get(criteria.getKey()), criteria.getValue());
}
}
...
答案 0 :(得分:0)
public class UserSpecification implements Specification<GeoMap> {
private SearchCriteria criteria;
public UserSpecification(SearchCriteria criteria) {
this.criteria = criteria;
}
@Override
public Predicate toPredicate
(Root<GeoMap> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
if (criteria.isEmpty()) return null;
//.. search something
}
}
然后
UserSpecification specName =
new UserSpecification(new SearchCriteria("name", ":", data.getName()));
UserSpecification specEnv =
new UserSpecification(new SearchCriteria("env", ":", data.getEnv()));
...
List list = gisMapRepository.findAll(Specification.where(specName).and(specEnv));