Home > OS >  JPA CascadeType.PERSIST triggers persist even if the parent is not persisting
JPA CascadeType.PERSIST triggers persist even if the parent is not persisting

Time:01-12

My problem is my application "works" although it shouldn't (AFAIK)

Every tutorial says that CascadeType.PERSIST causes a child to be persisted automatically when his parent is persisted. And it is usually followed by an example with explicit em.persist(parent)

My code looks like this (simplified):

@Entity
class Parent(
    @OneToMany(cascade = [CascadeType.PERSIST])
    val children: List<Child>
)

fun addChild() {
    val parent = parentRepository.find(id)
    val child = new Child()
    parent.children.add(child)
    // childRepository.save(child) is missing here but surprisingly the child is persisted
}

It seems CascadeType.PERSIST is triggered when the parent's collection is modified. Is it right? (I am using Hibernate 5.6.8, Spring 5.3.19 and Spring Data 2.6.4)

CodePudding user response:

This is the correct behavior according to section 3.2.4 of the JPA specification, covering discovering changes during synchronization to the database:

If X is a managed entity, it is synchronized to the database.

  • For all entities Y referenced by a relationship from X, if the relationship to Y has been annotated with the cascade element value
    cascade=PERSIST or cascade=ALL, the persist operation is applied to Y.
  • Related