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?
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.
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.
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.
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:
In 4.3 Hibernate with JPA, one can use "@CreationTimestamp" and "@UpdateTimestamp" directly in the date fields
CreationTimestamp java doc
UpdateTimestamp java doc
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With