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


Take your skills to the next level!

The Persistence Hub is the place to be for every Java developer. It gives you access to all my premium video courses, monthly Java Persistence News, monthly coding problems, and regular expert sessions.


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.

@Entity
public class Author {

	…

	@ManyToMany(mappedBy=”authors”, cascade = CascadeType.PERSIST)
	private List<Book> books = new ArrayList<Book>();

	…
}

When you now create a new Author and several associated Book entities, you just have to persist the Author entity.

EntityManager em = emf.createEntityManager();
em.getTransaction().begin();

Author a = new Author();
a.setFirstName(“John”);
a.setLastName(“Doe”);

Book b1 = new Book();
b1.setTitle(“John’s first book”);
a.getBooks().add(b1);

Book b2 = new Book();
b2.setTitle(“John’s second book”);
a.getBooks().add(b2);

em.persist(a);

em.getTransaction().commit();
em.close();

As you can see in the log output, Hibernate cascades the operation to the associated Book entities and persists them as well.

15:44:28,140 DEBUG [org.hibernate.SQL] – insert into Author (firstName, lastName, version, id) values (?, ?, ?, ?)
15:44:28,147 DEBUG [org.hibernate.SQL] – insert into Book (publisherid, publishingDate, title, version, id) values (?, ?, ?, ?, ?)
15:44:28,150 DEBUG [org.hibernate.SQL] – insert into Book (publisherid, publishingDate, title, version, id) values (?, ?, ?, ?, ?)

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!

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.