Hibernate Tips is a new 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.
I want to initialize an entity attribute automatically before it gets persisted. How can I execute custom code before Hibernate persists an entity?
Don’t want to read? You can watch it here!
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.
Get this Hibernate Tip as a printable PDF!Join the free Thoughts on Java Library to get access to lots of member-only content, like a printable PDF for this post, lots of cheat sheets and 2 ebooks about Hibernate.
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 @PreRemove annotation to execute custom code before Hibernate deletes an entity, as I do in this post: How to implement a soft delete with Hibernate.
Hibernate Tips Book
It gives you more than 70 ready-to-use recipes for topics like basic and advanced mappings, logging, Java 8 support, caching and statically and dynamically defined queries.
Get it now as a paperback, ebook or PDF.