Hibernate Tips: How to cascade a persist operation to child entities

By Thorben Janssen

Mapping

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.

Question:

How can I persist an entity together with all its child entities?

Solution:

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.

Learn More:

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!



Tags

Mapping


About the author

Thorben is an independent consultant, international speaker, and trainer specialized in solving Java persistence problems with JPA and Hibernate.
He is also the author of Amazon’s bestselling book Hibernate Tips - More than 70 solutions to common Hibernate problems.

Books and Courses

Coaching and Consulting

Leave a Reply

Your email address will not be published. Required fields are marked

This site uses Akismet to reduce spam. Learn how your comment data is processed.

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}