动态条件配置,使用泛型"T"作为实体类标识,在使用过程中替换成自己的实体类
/**
* 部分import引用
*/
import org.springframework.data.jpa.domain.Specification;
import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;
public class MessageSpec {
public static Specification<T> messageSpec(MessageJson messageJson){
return new Specification<T>() {
@Override
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
List<Predicate> whereList = new ArrayList<>();
if(EmptyUtil.isNotEmpty(messageJson.getUserId())) {
whereList.add(cb.equal(root.get("userId"), messageJson.getUserId()));
}
whereList.add(cb.between(root.get("notificationTime"), messageJson.getStartTime(), messageJson.getEndTime()));
Predicate[] pre = new Predicate[whereList.size()];
return query.where(whereList.toArray(pre)).getRestriction();
}
};
}
}
方法调用示例
Page<T> Messagepage = messageDao.findAll(MessageSpec.messageSpec(message),pageable);
pom.xml配置依赖
<!-- jpa -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>