休眠5:上次修改的自动更新的时间戳字段
我在Hibernate 5中有一个实体,该实体具有创建和上次修改的时间戳.我希望他们获得自动更新.
I have an entity in Hibernate 5, which have creation and last modified timestamps. I want them to get auto update.
/**
* Time of creation of entity
*/
@Column(name = "created_on", nullable = false)
private Timestamp createdOn;
/**
* Time of last update
*/
@Column(name = "last_update", nullable = false)
private Timestamp lastUpdate;
我是使用Hibernate 4做到的,使用映射xml文件如下:
I did it with Hibernate 4, using mapping xml file as follow :
<property name="createdOn" type="java.sql.Timestamp" generated="insert" not-null="true">
<column name="created_on" sql-type="timestamp" default="CURRENT_TIMESTAMP"/>
</property>
<property name="lastUpdate" type="java.sql.Timestamp" generated="always" not-null="true">
<column name="last_update" sql-type="timestamp" default="CURRENT_TIMESTAMP"/>
</property>
但是不知道如何在Hibernate 5中使用注释.
But don't know how to do it in Hibernate 5 using annotations.
方法1:
您可以使用类似以下的内容:
You can use something like below:
@PrePersist
protected void onCreate() {
createdOn = new Date();
}
@PreUpdate
protected void onUpdate() {
lastUpdate = new Date();
}
注意:如果您使用的是Session
API,则JPA回调将不起作用.
Note: JPA callbacks won't work if you are using Session
API.
方法2:
您可以使用@Version
注释对lastUpdate
字段进行注释.除了自动填充字段外,还将为实体引入乐观锁定.对于createdOn
字段,您可以简单地在实体的默认构造函数中对其进行初始化.
You can annotate lastUpdate
field with @Version
annotation. Apart from auto-populating the field it will also introduce optimistic locking for the entity. For the createdOn
field, you can simply initialize it in the default constructor of the entity.
方法3:
使用事件侦听器并手动更新相关属性.您需要创建一个扩展DefaultSaveOrUpdateEventListener
并覆盖onSaveOrUpdate
方法的侦听器.不要忘记注册事件监听器.
Use event listeners and update the relevant properties manually. You need to create a listener that extends DefaultSaveOrUpdateEventListener
and override the onSaveOrUpdate
method. Don't forget to register the event listener.
方法4:
您还可以分别在createdOn
和lastUpdate
字段中使用@CreationTimestamp
和@UpdateTimestamp
注释.
Method 4:
You can also use @CreationTimestamp
and @UpdateTimestamp
annotations for the createdOn
and lastUpdate
fields respectively.