在Java 11上使用Hibernate 5.3 / JPA 2.2@Version LocalDateTime作为字段



考虑一个名为Template的实体,其中包含一个字段:

@Version
@Column(name = "LAST_UPDATE", nullable = false)
private LocalDateTime lastUpdate; // Java 8's class

后备 Oracle 数据库字段为TIMESTAMP

现在执行以下代码:

// get EntityManager, start transaction
final var t = new Template();
t.setName("new template");
t.setSubject("subject");
em.persist(t);
t.setSubject("subject - mod");
tx.commit();

导致引发异常:

Caused by: org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) : [Template#169]
at org.hibernate.persister.entity.AbstractEntityPersister.check(AbstractEntityPersister.java:2525)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3357)
at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:3231)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3632)
at org.hibernate.action.internal.EntityUpdateAction.execute(EntityUpdateAction.java:146)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:604)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:478)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:356)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1453)
... 59 common frames omitted

如果我将lastUpdate类型更改为java.sql.Timestamp,则代码可以正常工作。可能是什么问题?

虽然文档中没有确切说明,但我认为 Hibernate 支持这种类型的@Version字段。

此处提供了测试用例:https://github.com/imeszaros/jooby-hbm-localdatetime

仅供记录:Oracle 的TIMESTAMP类型默认精度为 6,只能存储毫秒。

然而,Java的LocalDateTime可能有纳秒,因此您需要在数据库中使用TIMESTAMP(9)才能在不损失精度的情况下存储值。

相关内容

  • 没有找到相关文章

最新更新