Kuldeep Yadav
Kuldeep Yadav

Reputation: 1816

Hibernate 5: Auto updated timestamp field for last modified

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;

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>

But don't know how to do it in Hibernate 5 using annotations.

Upvotes: 4

Views: 7527

Answers (2)

Mubin
Mubin

Reputation: 4239

Method 1:

You can use something like below:

@PrePersist
protected void onCreate() {
createdOn = new Date();
}

@PreUpdate
protected void onUpdate() {
 lastUpdate = new Date();
}

Note: JPA callbacks won't work if you are using Session API.

Method 2:

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.

Method 3:

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.

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

Upvotes: 6

mahendran manickam
mahendran manickam

Reputation: 74

worth to use setter method

public void setLastUpdate ( TimeStamp lastu ) {
   this.lastUpdate = lastu == null ? 0 : new Date);
}

Upvotes: 0

Related Questions