Reputation: 2916
@Entity
@Table(name="transactions")
@NamedQuery(name="Transaction.findAll", query="SELECT t FROM Transaction t")
public class Transaction implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id", nullable=false, unique=true, length=11)
private int id;
@CreationTimestamp
@Column(name="created_at")
private Date createdAt;
}
I have above entity using with Hibernate. I have a requirement where I need to update createdAt field but when I try following it didn't work. The createdAt is from the date of creations, which make sense.
Transaction newTransaction = new Transaction();
newTransaction.setCreatedAT(new Date);
sessionFactory.openSession().save(newTransaction);
Is there a way to keep @CreationTimestamp annotation and be able to modify or set another date when needed ?
**I am using Hibernate 4 with Spring. Any solution or another suggestion will be highly appreciated **
Upvotes: 1
Views: 873
Reputation: 3176
Why would you want to set it manually? Much cleaner solution would be to have 2 methods in your entity class. Both annotations are from the persistence package.
private Date creationTime;
private Date modificationTime;
@PrePersist
public void prePersist() {
Date now = Date();
this.creationTime = now;
this.modificationTime = now;
}
@PreUpdate
public void preUpdate() {
this.modificationTime = Date();
}
Or preferably use Java 8/Jodatime classes, in which case you need set @Type
for fields manually as Hibernate doesn't support them out of the box as far as I know.
Upvotes: 4