Reputation: 8357
edit: I misinterpreted the hibernate documentation, @PrePersist
does exactly what I wanted. Stackoverflow won't let me delete the question so I'll leave it here for other's amusement.
Is there a callback in Hibernate before an Entity is persisted for the first time? I have some computations that should be done on the entity before it is saved for the first time but should not be repeated once the entity has been written to the DB once.
I am looking for something like @PrePersist
but that gets called only before the first persist.
Upvotes: 2
Views: 991
Reputation: 40036
@PrePersist
is going to be called only once when an entity is persisted. In Hibernate, if you are persisting same entity multiple times, the latter tries will not be successful because the entity is already persisted before, hence there will not be any cases of @PrePersist
called more than once for an entity
Upvotes: 2
Reputation: 9187
If you don't want to implement your computation inside of @PrePersist
annotated method, you can try to set Entity Interceptor if you open new hibernate session:
Session session = sessionFactory.openSession(new MyBeforePersistInterceptor());
Upvotes: 0
Reputation: 13272
Yes. In your @PrePersist
call you can perform the action only once. You need a flag that will tell you if the action was not performed already.
Upvotes: 0