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

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

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

public List 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(){
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) {
                List 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);
    }

 

你可能感兴趣的:(Spring-data-jpa时间按照between and 查询)