且构网

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

休眠5:上次修改的自动更新的时间戳字段

更新时间:2023-02-14 21:18:22

方法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: 您还可以分别在createdOnlastUpdate字段中使用@CreationTimestamp@UpdateTimestamp注释.

Method 4: You can also use @CreationTimestamp and @UpdateTimestamp annotations for the createdOn and lastUpdate fields respectively.