Reputation: 43
I want to use @org.hibernate.annotations.Generated to update 'lastModified' field automatically, Here is my code:
Bill:
@Entity
public class Bill {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
protected Long id;
@Temporal(TemporalType.TIMESTAMP)
@Column(insertable = false, updatable = false)
@org.hibernate.annotations.Generated(GenerationTime.ALWAYS)
protected Date lastModified;
@Column
protected String description;
public void setDescription(String description) {
this.description = description;
}
public Date getLastModified() {
return lastModified;
}
public void setLastModified(Date lastModified) {
this.lastModified = lastModified;
}
public String getDescription() {
return description;
}
}
Main:
public static void main(String[] args) {
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
Bill bill1 = new Bill();
session.persist(bill1);
Bill bill2 = new Bill();
session.persist(bill2);
bill1.setDescription("Bill1 modified");
tx.commit();
factory.close();
}
When I checked bills by sql manually, it showed:
id | description | lastModified |
--- | -------------- | ---------------- |
1 | Bill1 modified | null
2 | null | null
My hibernate version is 5.2.9.Final, and mysql version is 5.7.16. I tried to remove 'insertable = false, updatable = false' but it didn't work either.
Upvotes: 2
Views: 2023
Reputation: 743
You can use @CreationTimestamp and @UpdateTimestamp instead:
@CreationTimestamp
private Date created;
@UpdateTimestamp
private Date lastModified;
Timestamp generated with theses annotations are in-memory generation based on VM time.
If you need timestamp generated by your database you must use a custom annotation, marked with @ValueGenerationType.
See the following link for details : http://docs.jboss.org/hibernate/orm/4.3/topical/html/generated/GeneratedValues.html#_in_database_generation
Upvotes: 3