import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import java.util.List;
public class DynamicSpecifications {
public static <T> Specification<T> bySearchFilter(List<SearchFilter> filters, Class<T> clazz) {
return new Specification<T>() {
@Override
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
List<Predicate> predicates = filters.stream()
.map(filter -> bySearchFilter(filter, root, cb))
.collect(Collectors.toList());
return cb.and(predicates.toArray(new Predicate[predicates.size()]));
}
};
}
private static <T> Predicate bySearchFilter(SearchFilter filter, Root<T> root, CriteriaBuilder cb) {
String fieldName = filter.getFieldName();
fieldName = fieldName.replace(".", "_"); // 替换为下划线,因为有些字段可能包含点,例如"user.name"
Path<?> path = root.get(fieldName);
String keyword = filter.getKeyword();
switch (filter.getOperation()) {
case EQ:
return cb.equal(path, keyword);
case LIKE:
return cb.like(path.as(String.class), "%" + keyword + "%");
case GT:
return cb.greaterThan(path.as(Integer.class), Integer.valueOf(keyword));
case LT:
return cb.lessThan(path.as(Integer.class), Integer.valueOf(keyword));
default:
return null;
}
}
// 使用示例
public static void main(String[] args) {
// 假设有一个UserRepository继承了JpaRepository和JpaSpecificationExecutor
UserRepository userRepository = ...; // 获取UserRepository的实例
// 创建SearchFilter列表
List<SearchFilter> filters = new ArrayList<>();
filters.add(new SearchFilter("name", SearchOperation.LIKE, "John"));
filters.add(new SearchFilter("age", Se
评论已关闭