【问题标题】:How to set datetimeoffset values in JPQL?如何在 JPQL 中设置 datetimeoffset 值?
【发布时间】:2019-08-29 09:42:45
【问题描述】:

我正在尝试扩展 CrudRepository 以实现软删除功能。参考this Q&A,我做了一个这样的仓库界面:

@NoRepositoryBean
public interface SoftDeleteCrudRepository<T extends SoftDelete, ID extends Long> extends CrudRepository<T, ID> {
    //...

    @Override
    @Query("update #{#entityName} e set e.delDT=current_timestamp where e.delDT is null and e.id=?1")
    @Modifying
    void deleteById(Long id);

    //...
}

该方法运行良好,但delDT 值不包含偏移值(例如2019-04-08 17:41:20.12 +00:00)。

我可以将 JPQL 更改为原生查询并使用 sysdatetimeoffset() 而不是 current_timestamp,但如果可以的话,我想继续使用 JPQL。

如何在 JPQL 中设置 datetimeoffset 值?

【问题讨论】:

  • CURRENT_TIMESTAMP for JPQL 的类型为java.sql.Timestampcheck this,不能不包含任何偏移值。我认为这些 JPQL 函数不可行,您可以尝试将 DateTimeOffset 对象与 id 参数一起传递到查询中? e.delDT=$2
  • @buræquete 我可以,但是我应该手动输入值有点可惜。
  • 你能试试吗?如果可行,我可以将其作为答案,否则遗憾的是,我看不到任何使用 JPQL 的方法... =/
  • @buræquete 我试过但失败了,结果相同。也许this issue是原因?
  • 哦,当然,DB中的偏移值总是相同的。您不能通过 +05:00 或 -03:00 等。它将全部映射到单个偏移量(由数据库或 JDBC 连接(我认为)定义),因此 DB 中的值将转移到所选时区.如果您想保留该信息,您应该有一个单独的列来存储时区数据。对不起,我误解了你的问题。

标签: sql-server hibernate spring-data-jpa jpql


【解决方案1】:

在 JPQL 中似乎没有办法做到这一点,所以我不得不采取一种解决方法。基本上,我使用了 SQL 服务器从varchardatetimeoffset 的隐式转换。所以这可能不适用于其他 DBMS。我像这样更改了存储库界面:

@NoRepositoryBean
public interface SoftDeleteCrudRepository<T extends SoftDelete, ID extends Long> extends CrudRepository<T, ID> {
    //...

    @Query("update #{#entityName} e set e.delDT=?2 where e.delDT is null and e.id=?1")
    @Modifying
    void deleteById(Long id, String datetimeStr);

    //...
}

然后像这样使用:

authRepository.deleteById(entity.getSeq(), OffsetDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS XXX")));

我还从实体类将delDT 字段类型从OffsetDatetime 更改为String。否则会出现这样的异常。

org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value [2019-04-10 11:53:13.189 +09:00] did not match expected type [java.time.OffsetDateTime (n/a)]; nested exception is java.lang.IllegalArgumentException: Parameter value [2019-04-10 11:53:13.189 +09:00] did not match expected type [java.time.OffsetDateTime (n/a)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-22
    • 2021-09-15
    • 2018-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多