In order to delete an object from the database it has to first be retrieved (no matter which way) and then in an active transaction, it can be deleted using the remove method:
Employee employee = em.find(Employee.class, 1); em.getTransaction().begin(); em.remove(employee); em.getTransaction().commit();
@Entity class Employee { : @OneToOne(cascade=CascadeType.REMOVE) private Address address; : }
In the example above, the Employee entity class contains an address field that references an instance of Address , which is another entity class. Due to the CascadeType.REMOVE setting, when an Employee instance is removed the operation is automatically cascaded to the referenced Address instance, which is then automatically removed as well. Cascading may continue recursively when applicable (e.g. to entity objects that the Address object references, if any).
JPA 2 supports an additional and more aggressive remove cascading mode which can be specified using the orphanRemoval element of the @OneToOne and @OneToMany annotations:
@Entity class Employee { : @OneToOne(orphanRemoval=true) private Address address; : }
When an Employee entity object is removed the remove operation is cascaded to the referenced Address entity object. In this regard, orphanRemoval=true and cascade=CascadeType.REMOVE are identical, and if orphanRemoval=true is specified, CascadeType.REMOVE is redundant.
The difference between the two settings is in the response to disconnecting a relationship. For example, such as when setting the address field to null or to another Address object.
To avoid dangling references as a result of orphan removal this feature should only be enabled for fields that hold private non shared dependent objects.
Orphan removal can also be set for collection and map fields. For example:
@Entity class Employee { : @OneToMany(orphanRemoval=true) private List<Address> addresses; : }
In this case, removal of an Address object from the collection leads to automatic removal of that object from the database.