更新时间: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:
您还可以分别在createdOn
和lastUpdate
字段中使用@CreationTimestamp
和@UpdateTimestamp
注释.
Method 4:
You can also use @CreationTimestamp
and @UpdateTimestamp
annotations for the createdOn
and lastUpdate
fields respectively.