规范CriteriaBuilder将ZonedDateTime转换为LocalDate以进行比较

时间:2018-01-11 23:50:34

标签: java mysql spring zoneddatetime

我需要比较一个实体的日期介于两个日期之间,遗憾的是我没有得到我需要的结果。条件构建器创建了一个比较日期和时间的查询,而不是比较日期,而不会返回任何结果。我使用Spring Specification来调用条件构建器。我的问题是我使用ZoneDateTime(我需要这个)来比较日期,我只是想知道是否离开我是否可以将这两个日期转换为LocalDate所以它会比较2018-01-12'而不是' 2018-01-12 09:45:00'。

Criteria Builder:

 public static Specification<Activity> activityDateBetween(ZonedDateTime from, ZonedDateTime to) {
        return new Specification<Activity>() {
            @Override
            public Predicate toPredicate(Root<Activity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Predicate startingFrom =  criteriaBuilder.greaterThanOrEqualTo(root.get(Activity_.date), from);
                Predicate endingAt = criteriaBuilder.lessThanOrEqualTo(root.get(Activity_.date), to);
                return criteriaBuilder.and(startingFrom, endingAt);
            }
        };
    }

MySQL的:

SELECT activity0_.id                  AS id1_5_, 
       activity0_.activity_type       AS activity2_5_, 
       activity0_.activity_date       AS activity3_5_, 
       activity0_.tracker_job_item_id AS tracker_5_5_, 
       activity0_.work_type           AS work_typ4_5_, 
       activity0_.tracker_worker_id   AS tracker_6_5_ 
FROM   tracker_job_item_activity activity0_ 
WHERE  activity0_.tracker_job_item_id = 71 
       AND ( activity0_.work_type IN ( 'BUTTONHOLING', 'SEWING', 'CUTTING' ) ) 
       AND ( activity0_.activity_type IN ( 'RECEIVE', 'SEND' ) ) 
       AND activity0_.activity_date >= '2018-01-12 09:29:43' 
       AND activity0_.activity_date <= '2018-01-12 09:29:43'

正如您所看到的,上面的查询是比较日期时间,这不是我想要的。

1 个答案:

答案 0 :(得分:1)

好吧,我已经设法通过从ZonedDateTime中减去时间部分来获得我想要的结果。现在搜索包含当前日期。

   public static Specification<Activity> activityDateBetween(ZonedDateTime from, ZonedDateTime to) {
            return new Specification<Activity>() {
                @Override
                public Predicate toPredicate(Root<Activity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                    Predicate startingFrom =  criteriaBuilder.greaterThanOrEqualTo(root.get(Activity_.date),
                        from.minusHours(from.getHour()).minusMinutes(from.getMinute()).minusSeconds(from.getSecond()));
                    Predicate endingAt = criteriaBuilder.lessThanOrEqualTo(root.get(Activity_.date), to);
                    return criteriaBuilder.and(startingFrom, endingAt);
                }
            };
        }