Hibernate Tips is a series of posts in which I describe a quick and easy solution for common Hibernate questions. If you have a question you like me to answer, please leave a comment below.
Get this Hibernate Tip as a printable PDF!I've created a printable PDF for this Hibernate Tip. As always, you can download it for free from the Thoughts on Java Library.
I want to initialize an entity attribute automatically before it gets persisted. How can I execute custom code before Hibernate persists an entity?
The JPA specification defines a set of callback annotations to trigger method calls for certain lifecycle events. If you want to initialize an entity attribute before it gets persisted, you just have to do 2 things:
- Add a method to the entity which initializes the attribute.
- Annotate this method with @PrePersist so that Hibernate calls it before it persists the entity.
You can see an example of such a method in the following code snippet.
Hibernate will call this method when it persists a new Author entity and trigger the initialization of the createdAt attribute. You can see that in the following log output. Hibernate calls the initializeCreatedAt method before it performs the SQL statements to get the primary key value and to persist the entity.
I get into more details about entity lifecycle events and the more advanced EntityListeners, in my Advanced Hibernate Training. I’m happy to see you there if you want to dive deeper into this topic.
The JPA specification also defines callback annotation for other entity lifecycle events. You can, for example, use the @PrePersist annotation to execute custom code before Hibernate deletes an entity, as I do in this post: How to implement a soft delete with Hibernate.