Spring-data-jpa时间按照between and 查询
需求:根据一个String类型的year,要求查询出该年的所有记录;
比如根据2018年查询出2018年01月01日到2018年12月31日之间的记录;
- public List<Rain> findAllByYear(String year) throws ParseException {
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- String start = year+"-01-01 00:00:00";
- String end = Integer.valueOf(year)+1+"-01-01 00:00:00";
- Date startTime = sdf.parse(start);
- Date endTime = sdf.parse(end);
- System.out.println(startTime);
- System.out.println(endTime);
- Specification querySpecifi = new Specification<Rain>(){
- @Override
- public Predicate toPredicate(Root<Rain> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
- List<Predicate> predicates = new ArrayList<>();
- if (year != null){
- predicates.add(criteriaBuilder.between(root.get("createTime"),startTime,endTime));
- }
- return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
- }
- };
- return rainDao.findAll(querySpecifi);
- }
原文地址:https://blog.csdn.net/m0_37501154/article/details/88542690