且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

很难用休眠JPA批注设置自动生成时间

更新时间:2021-12-13 09:41:54

这与Hibernate本身无关。上面指定的注释告诉Hibernate这些值将由数据库生成,因此需要在插入/更新实体后重新加载。

This is not related to Hibernate per se. Your annotations as specified above tell Hibernate that the values are going to be generated by the database and thus need to be reloaded after entity is inserted / updated.

如果这样你需要配置你的数据库(例如通过创建一个触发器)来填充 date_created / last_modified 列。

If that's the way you want to go with, you need to configure your database (by creating a trigger, for example) to populate date_created / last_modified columns as needed.

另一种方法是不要将这些字段标记为生成的,而是在您的java代码中更新它们。如果你使用JPA(通过Hibernate EntityManager),通过 @ PrePersist / @PreUpdate 回调方法:

Another approach is to not mark those fields as generated and instead update them in your java code. If you're using JPA (via Hibernate EntityManager), it's rather trivial to do this via @PrePersist / @PreUpdate callback method:

@PreUpdate
@PrePersist
public void updateTimeStamps() {
    lastModified = new Date();
    if (dateCreated==null) {
      dateCreated = new Date();
    }
}