其他分享
首页 > 其他分享> > Spring-data-jpa时间按照between and 查询

Spring-data-jpa时间按照between and 查询

作者:互联网

需求:根据一个String类型的year,要求查询出该年的所有记录;

比如根据2018年查询出2018年01月01日到2018年12月31日之间的记录;

  1. public List<Rain> findAllByYear(String year) throws ParseException {
  2. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  3. String start = year+"-01-01 00:00:00";
  4. String end = Integer.valueOf(year)+1+"-01-01 00:00:00";
  5. Date startTime = sdf.parse(start);
  6. Date endTime = sdf.parse(end);
  7. System.out.println(startTime);
  8. System.out.println(endTime);
  9. Specification querySpecifi = new Specification<Rain>(){
  10. @Override
  11. public Predicate toPredicate(Root<Rain> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
  12. List<Predicate> predicates = new ArrayList<>();
  13. if (year != null){
  14. predicates.add(criteriaBuilder.between(root.get("createTime"),startTime,endTime));
  15. }
  16. return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
  17. }
  18. };
  19. return rainDao.findAll(querySpecifi);
  20. }

原文地址:https://blog.csdn.net/m0_37501154/article/details/88542690

标签:00,01,String,jpa,Spring,between,year,predicates,new
来源: https://www.cnblogs.com/jpfss/p/11214219.html