很难用休眠JPA批注设置自动生成时间 [英] hard time setting autogenerated time with hibernate JPA annotations

查看:199
本文介绍了很难用休眠JPA批注设置自动生成时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

感谢你们,我对hibernate的了解得到了改善。
现在我在这里打开一个关于current_timestamp的块。
这里是我的代码

thanks to you guys my knowlegde on hibernate has been improve dratiscally. now i hit a block here about current_timestamp. here is my codes

@Column(name="DATE_CREATED", insertable=false, updatable=false, columnDefinition="timestamp default current_timestamp")
@org.hibernate.annotations.Generated(value=GenerationTime.INSERT)
@Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Date dateCreated;

@Column(name="LAST_MODIFIED", insertable=false, updatable=false, columnDefinition="datetime")
@org.hibernate.annotations.Generated(value=GenerationTime.ALWAYS)
@Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Date lastModified;

我希望date_created获得current_timestamp,我希望lastmodified为每个updates.apparently插入时间我不能在同一张桌子上有两个current_timestamp字段。是否有其他方法可以实现这一点?感谢阅读

i want date_created to get the current_timestamp and i want the lastmodified to insert the time for each updates.apparently i can't have 2 current_timestamp fields on the same table.Is there other ways to achieve that? thanks for reading

推荐答案

这与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();
    }
}

这篇关于很难用休眠JPA批注设置自动生成时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆