Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to autogenerate created or modified timestamp field?

Tags:

My entity class:

@Entity @Table(name = "user") public class User implements Serializable {     private static final long serialVersionUID = 1L;      @Id     @SequenceGenerator(name = "USER_ID_GENERATOR", sequenceName = "USER_SEQ")     @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "USER_ID_GENERATOR")     @Column(name = "user_id")     private long userId;       @Temporal(TemporalType.DATE)     private Date created;      @Temporal(TemporalType.DATE)     private Date modified;      //setters and getters... } 

I would like to CREATED and MODIFIED fields complement each other automatically when you create or modify the object. CREATED and MODIFIED fields should be of type TIMESTAMP.

How do I achieve that?

like image 220
tomasz-mer Avatar asked Mar 10 '11 09:03

tomasz-mer


People also ask

How do I add a modified timestamp field to an existing table?

So, to add your modified timestamp field to an existing table, all you need is: Adding a CreateTime value is a little more involved. On the latest versions of MySQL it is apparently possible to create a DateTime field with a default value of CURRENT_TIMESTAMP.

Why is the created timestamp later than the updated timestamp?

Keep this in mind, as you may encounter rows where the “created” timestamp (which is a regular column default) is slightly later than the “updated”, because of this phenomena. This may be a problem or a feature depending on your use case.

How do I use the timestamp attribute in Entity Framework?

Entity Framework API automatically uses this Timestamp column in concurrency check on the UPDATE statement in the database. In the above example, the Timestamp attribute is applied to the byte [] property of the Student entity.

Can I have multiple timestamp fields in a row?

While you can have multiple TIMESTAMP fields in a row, only one of these can be automatically updated with the current time on update. If your UPDATE query contains a value for your ModifiedTime field, this value will be used. So, to add your modified timestamp field to an existing table, all you need is:


2 Answers

In 4.3 Hibernate with JPA, one can use "@CreationTimestamp" and "@UpdateTimestamp" directly in the date fields

CreationTimestamp java doc

UpdateTimestamp java doc

like image 71
Rajesh Avatar answered Sep 19 '22 23:09

Rajesh


You can just create a new Date() whenever your instance is created, and then update the updated field whenever the entity gets updated:

private Date created = new Date(); private Date updated = new Date();  @PreUpdate public void setLastUpdate() {  this.updated = new Date(); } 

Don't provide a setter for any of these methods, only getters.

like image 39
jpkrohling Avatar answered Sep 22 '22 23:09

jpkrohling