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.
How can I persist an entity together with all its child entities?
Don’t want to read? You can watch it here!
You can tell Hibernate, and any other JPA implementation, to cascade certain operations you perform on an entity to its associated child entities. The only thing you have to do is to define the kind of operation you want to cascade to the child entities.
The following code snippet shows an example in which I cascade the persist operation of the Author entity to all associated Book entities.
When you now create a new Author and several associated Book entities, you just have to persist the Author entity.
As you can see in the log output, Hibernate cascades the operation to the associated Book entities and persists them as well.
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 the different cascading options in my Advanced Hibernate Training. I’m happy to see you there if you want to dive deeper into this topic.
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.