【问题标题】:How to fetch an entity having a timestamp property that is within an hour from other timestamp property with JPA and Hibernate如何使用 JPA 和 Hibernate 从其他时间戳属性中获取时间戳属性在一小时内的实体
【发布时间】:2019-06-13 20:38:09
【问题描述】:

我对带有路径或表达式的 JPA 查询条件生成器有疑问。

我想找出在创建帐户后一小时内首次发表评论的人

Path<Date> accountCreatedTime = root.<Date> get("AccountCreatedTime");
Path<Date> firstPostCreatedTime = root.<Date> get("FirstPostCreatedTime");

final Predicate timeInHourPredicate = criteriaBuilder
    .greaterThanOrEqualTo(accountCreatedTime, FirstPostCreatedTime);

例子:

  1. 帐户创建于:2018 年 9 月 10 日上午 10 点,第一次发布于 2018 年 9 月 10 日上午 10 点 15 分输入,应获取此回复。 (一小时内下降)

  2. 帐户创建于:2018 年 9 月 10 日上午 10 点,第一篇帖子于 2018 年 9 月 10 日下午 3.50 输入,不应获取此信息。

有什么方法可以从 Path accountCreatedTime 中添加或分隔小时数?或者我们能否在小时数和标准构建器中获得路径 accountCreatedTime 和 Path FirstPostCreatedTime 之间的差异

【问题讨论】:

    标签: hibernate jpa spring-data-jpa jpa-2.1 hibernate-jpa


    【解决方案1】:

    使用 DATEDIFF

    SQL 应该是这样的:

    select u
    from users u
    join posts p on p.user_id = u.id
    where datediff('hour', u.account_created_time, p.first_post_created_time)
    

    有关如何使用 Criteria API 注册 DATEDIFF 函数的更多详细信息,请查看 this article

    【讨论】:

    • 路径 accountCreatedTime = root。获取(“帐户创建时间”);路径 FirstPostCreatedTime = 根。 get("FirstPostCreatedTime"),由于各种其他条件,我们正在使用路径并使用标准构建器
    • 只需将 SQL 查询转换为 Criteria API 即可。如果你想用greaterThanOrEqualTo来做,你需要查询,这样效率较低。
    • 路径 accountCreatedTime = root。获取(“帐户创建时间”);路径 FirstPostCreatedTime = 根。 get("FirstPostCreatedTime"),由于各种其他条件和使用标准构建器,我们正在使用路径。请假设第一个帖子创建时间和帐户创建时间列在同一个表中。
    • 是的,我试过了,像这样。 MS Sql Server ' String functionName="Dateiff" Predicate predicate=cb.greaterThan(builder.function(functionName,Integer.class,builder.literal("MINUTE"),PostEnteredDateTM, accountCreatedTM), 60 );'错误是:为 datediff 指定的参数 1 无效。
    猜你喜欢
    • 1970-01-01
    • 2017-01-18
    • 1970-01-01
    • 1970-01-01
    • 2011-02-19
    • 2018-07-13
    • 1970-01-01
    • 2021-12-25
    相关资源
    最近更新 更多