tags:

views:

425

answers:

2

I have to auto generate timestamp when I am creating a new record and auto generate modified timestamp when I update a record.

can anybody tell me how do I implement this. I am using openJPA.

thanks in advance.

A: 

The easiest is to use @Version annotation (documentation here)

Just add the following to your entities:

@Version
private java.sql.Timestamp myTimestamp;

/// normal getters & setters here

And it will do it automatically

Gregory Mostizky
@Version is used only for updating - The creation date will be lost
David Rabinowitz
I am 99% sure it is also used for creation - otherwise how it would do the first update? Do you have any reference that says @Version is not updated on creation?
Gregory Mostizky
Isn't @Version used in conjunction with locking? What if you don't want to use locking but just want timestamp?
Shervin
+1  A: 

You can use the following code:

@Column
@Temporal(TemporalType.TIMESTAMP)
private Date creationDate;

@Column
@Temporal(TemporalType.TIMESTAMP)
private Date lastModificationDate;

// getters, setters

@PrePersist
void updateDates() {
  if (creationDate == null) {
    creationDate = new Date();
  }
  lastModificationDate = new Date();
}
David Rabinowitz
Shouldn't you include @PreUpdate also? Or will update also run on @PrePersist
Shervin