1

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

标准生成器:

 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'

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

4

1 回答 1

2

好吧,通过从 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);
                }
            };
        }
于 2018-01-12T00:25:38.927 回答