Spring Data JPA时间戳比较

时间:2018-10-12 07:46:46

标签: java sql spring-data-jpa db2

我正在尝试将本机查询转换为规范。我被困在这种情况下:

....
WHERE
TIMESTAMP(D_DATA, D_TIME) >= '2015-06-23 05:46:53.000000'

是否可以通过“规范”获得相同的结果?

谢谢

2 个答案:

答案 0 :(得分:1)

不确定是否有帮助,但是该过滤器也可以在Db2中这样编写。

WHERE
     D_DATA >= '2015-06-23'
OR ( D_DATA  = '2015-06-23' AND D_TIME >= '05:46:53' )

答案 1 :(得分:0)

感谢保罗·弗农(Paul Vernon),我的决定是:

public static Specification<Transit>compareTimestamps(Timestamp timestamp){
    LocalTime localTime = timestamp.toLocalDateTime().toLocalTime();
    LocalDate localDate = timestamp.toLocalDateTime().toLocalDate();
    Specification<Transit> dateSpec = compareDateWithTimestamp(localDate);
    Specification<Transit> dateTimeSpec = compareDateAndTimeWithTimestamp(localDate, localTime);
    return where(dateSpec).or(dateTimeSpec);
}

private static <T>Specification<T> compareDateWithTimestamp(LocalDate localDate){
    return (Specification<T>) (root,query,cb) -> cb.greaterThan(root.get("dTrn"),localDate);
}
private static <T>Specification<T> compareDateAndTimeWithTimestamp(LocalDate localDate, LocalTime localTime){
    return (Specification<T>) (root, query, cb) -> {
        List<Predicate> predicates = new ArrayList<>();
        predicates.add(cb.equal(root.get("dTrn"),localDate));
        predicates.add(cb.greaterThanOrEqualTo(root.get("dTimTrn"),localTime));
        return cb.and(predicates.toArray(new Predicate[]{}));
    };
}