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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM