Prakash Rajagaopal
Prakash Rajagaopal

Reputation: 602

How to auto generate the timestamp in a entity bean in hibernate?

How does one auto generate the timestamp in a entity bean in hibernate?

Does the @Generator have anything to directly put in it like:

@GeneratedValue(vale=new Date().getTime())

Upvotes: 1

Views: 1889

Answers (3)

Boris Treukhov
Boris Treukhov

Reputation: 17784

You can implement global EntityInterceptor:

public class GlobalEntityInterceptor 
    extends EmptyInterceptor {
    @Override
    public boolean onSave(java.lang.Object entity, java.io.Serializable p2, java.lang.Object[] p3, java.lang.String[] p4, org.hibernate.type.Type[] p5) {   
  //first save - you can modify your entity fields
}
    @Override
    public boolean onFlushDirty(java.lang.Object entity, java.io.Serializable p2, java.lang.Object[] p3, java.lang.Object[] p4, java.lang.String[] p5, 
                                    org.hibernate.type.Type[] p6) { 
  //modification  - you can modify your entity fields 

}

there are some annotation-driven solutions like @PrePersist, but they only work in few environments.

Upvotes: 1

Timii
Timii

Reputation: 234

You could use hibernates interceptors for populating entities with some data ie. creation date etc.

Read here for more information about interceptors

Upvotes: 0

Alexander Rühl
Alexander Rühl

Reputation: 6959

You cannot put some code into the annotation, you just provide the values.

For automatically updating a timestamp at every change to the entity, you can use @Version on a timestamp field:

   @Version
   private Timestamp lastUpdate;

Upvotes: 1

Related Questions