Search code examples
jpaentitymanager

Difference between cascade remove and explicit remove


Suppose we have 2 entity classes Employee and Address and Address class is referenced in the Employee class:

@Entity
class Employee {
    :
  @OneToOne
  private Address address;
    :
}

If we use explicit remove:

Employee employee = em.find(Employee.class, 1);

em.getTransaction().begin();
em.remove(employee);
em.getTransaction().commit();

I know it will remove employee instance from the Employee table, but does it also remove the referenced address instance from the Address table? Or should we explicitly use remove on that address instance to remove it from the Addresstable?


Solution

  • From the documentation of @OneToOne, by default no operations are cascaded. That means in your case the address is not removed when you remove the employee.

    See also : CascadeType