java规范criteriabuilder将ZoneDateTime转换为localdate进行比较

eoxn13cs  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(351)

我需要比较一个实体有一个介于两个日期之间的日期,不幸的是我没有得到我需要的结果。criteria builder没有比较日期,而是创建了一个比较日期和时间的查询,结果不会返回任何结果。我使用spring规范来调用criteriabuilder。我的问题是,我使用zonedatetime(我需要这个)来比较日期,我只是想知道是否有away如果有away,我可以将两个日期都转换为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'

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

pwuypxnk

pwuypxnk1#

好吧,我已经设法得到我想要的结果,从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);
                }
            };
        }

相关问题