【问题标题】:JOOQ localDateTimeDiff with java.time.Duration'sJOOQ localDateTimeDiff 与 java.time.Duration\'s
【发布时间】:2022-10-17 16:46:17
【问题描述】:

我有一个带有创建时间戳 (timestamp) 和生存时间 (interval) 的表。

CREATE TABLE my_object (
   id uuid NOT NULL PRIMARY KEY,
   created timestamp NOT NULL,
   time_to_live interval NOT NULL
);

现在我想找到所有对象,它们的 TTL 结束了。我试过这样的事情:

public class MyObjectRepository {

  public Stream<MyObjectDto> fetchExpired() {
    return context
        .selectFrom(MY_OBJECT)
        .where(localDateTimeDiff(currentLocalDateTime(), MY_OBJECT.CREATED)
            .greaterThan(MY_OBJECT.TIME_TO_LIVE))
            // ^- compile-error, no overload accepts TableField<MyObjectRecord, Duration>
        .forUpdate()
        .skipLocked()
        .fetchStreamInto(MyObjectDto.class);
  }
}

也许这里的大问题是,我将 TTL 强制输入java.time.Duration。但对于干净的 API,我无法将类型更改为 DayToSecond

<!-- others -->
<forcedType>
   <userType>java.time.Duration</userType>
   <converter>org.jooq.Converter.ofNullable(
      org.jooq.types.YearToSecond.class, Duration.class,
      yearToSecond -> yearToSecond.toDuration(), duration -> org.jooq.types.YearToSecond.valueOf(duration)
       )
   </converter>
   <includeTypes>INTERVAL</includeTypes>
</forcedType>
<!-- others -->

我怎样才能在 JOOQ 中做到这一点?

【问题讨论】:

    标签: java jooq


    【解决方案1】:

    使用 Duration 类方法 from() 与您的 TTL 以创建具有您的 TTL 间隔的 Duration 实例,然后使用 Duration 方法 addTo() 与创建时间来获取您的 TTL 到期的时刻。将该时刻与当前时间进行比较,如果当前时间在您的过期时间之后,那么您的记录就过期了。请参阅持续时间 Javadoc here

    【讨论】:

      【解决方案2】:

      我的解决方案有点朝着Michael Gantmans 答案的方向发展,但我没有让它起作用。

      所以......我稍微改变了 SQL 表。新架构如下所示:

      CREATE TABLE my_object (
         id uuid NOT NULL PRIMARY KEY,
         created timestamp NOT NULL,
         valid_until timestamp NOT NULL
      );
      

      使用新模式,让 JOOQ 工作变得非常容易。代码简化为:

      public Stream<MyObjectDto> fetchExpired() {
        return context
            .selectFrom(MY_OBJECT)
            .where(MY_OBJECT.VALID_UNTIL.lessThan(ZonedDateTime.now()))
            .fetchStreamInto(MyObjectDto.class);
      }
      

      新架构还有其他一些优点:

      • 性能更高,因为不得为每次运行重新计算 eol-time
      • 性能更高²,因为valid_until 可以被索引
      • 不破坏API,因为如果需要可以计算Duration的TTL(valid_until - created

      【讨论】:

        猜你喜欢
        • 2015-11-20
        • 1970-01-01
        • 2017-07-01
        • 2020-06-12
        • 2020-07-30
        • 2014-02-14
        • 1970-01-01
        • 2020-10-01
        • 2013-11-28
        相关资源
        最近更新 更多