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.
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.