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?
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.
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
Get more recipes like this one in my new book Hibernate Tips: More than 70 solutions to common Hibernate problems.
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!