休眠5:上次修改的自动更新的时间戳字段 [英] Hibernate 5: Auto updated timestamp field for last modified

查看:90
本文介绍了休眠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: 您还可以分别在createdOnlastUpdate字段中使用@CreationTimestamp@UpdateTimestamp注释.

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

这篇关于休眠5:上次修改的自动更新的时间戳字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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