Deleting JPA Entity Objects
Existing entity objects can be deleted from the database either explicitly by invoking the removeremove(entity)EntityManager's methodRemove the entity instance.See JavaDoc Reference Page...
method or implicitly as a result of a cascade operation.
This page covers the following topics:
Explicit Remove
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 removeremove(entity)EntityManager's methodRemove the entity instance.See JavaDoc Reference Page...
method:
Employee employee = em.findfind(entityClass, primaryKey)EntityManager's methodFind by primary key.See JavaDoc Reference Page...(Employee.class, 1); em.getTransactiongetTransaction()EntityManager's methodReturn the resource-level EntityTransaction object.See JavaDoc Reference Page...().beginbegin()EntityTransaction's methodStart a resource transaction.See JavaDoc Reference Page...(); em.removeremove(entity)EntityManager's methodRemove the entity instance.See JavaDoc Reference Page...(employee); em.getTransactiongetTransaction()EntityManager's methodReturn the resource-level EntityTransaction object.See JavaDoc Reference Page...().commitcommit()EntityTransaction's methodCommit the current resource transaction, writing any unflushed changes to the database.See JavaDoc Reference Page...();
The entity object is physically deleted from the database when the transaction is committed. Embedded objects that are contained in the entity object are also deleted. If the transaction is rolled back and not committed the object is not deleted.
An IllegalArgumentException
is thrown by removeremove(entity)EntityManager's methodRemove the entity instance.See JavaDoc Reference Page...
if the argument is not an instance of an entity class or if it is a detached entity. A TransactionRequiredException
javax.persistence.TransactionRequiredExceptionJPA exceptionThrown by the persistence provider when a transaction is required but is not active.See JavaDoc Reference Page... is thrown if there is no active transaction when remove
is called because operations that modify the database require an active transaction.
Cascading Remove
Marking a reference field with CascadeTypejavax.persistence.CascadeTypeJPA enumDefines the set of cascadable operations that are propagated to the associated entity.See JavaDoc Reference Page....REMOVECascadeType.REMOVEenum constantCascade remove operationSee JavaDoc Reference Page...
(or CascadeTypejavax.persistence.CascadeTypeJPA enumDefines the set of cascadable operations that are propagated to the associated entity.See JavaDoc Reference Page....ALLCascadeType.ALLenum constantCascade all operationsSee JavaDoc Reference Page...
, which includes REMOVECascadeType.REMOVEenum constantCascade remove operationSee JavaDoc Reference Page...
) indicates that removeremove(entity)EntityManager's methodRemove the entity instance.See JavaDoc Reference Page...
operations should be cascaded automatically to entity objects that are referenced by that field (multiple entity objects can be referenced by a collection field):
@Entityjavax.persistence.EntityJPA annotationSpecifies that the class is an entity.See JavaDoc Reference Page... class Employee { : @OneToOnejavax.persistence.OneToOneJPA annotationDefines a single-valued association to another entity that has one-to-one multiplicity.See JavaDoc Reference Page...(cascadeOneToOne.cascadeannotation element(Optional) The operations that must be cascaded to the target of the association.See JavaDoc Reference Page...=CascadeTypejavax.persistence.CascadeTypeJPA enumDefines the set of cascadable operations that are propagated to the associated entity.See JavaDoc Reference Page....REMOVECascadeType.REMOVEenum constantCascade remove operationSee JavaDoc Reference Page...) 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).
Orphan Removal
JPA 2 supports an additional and more aggressive remove cascading mode which can be specified using the orphanRemoval
element of the @OneToOne
javax.persistence.OneToOneJPA annotationDefines a single-valued association to another entity that has one-to-one multiplicity.See JavaDoc Reference Page... and @OneToMany
javax.persistence.OneToManyJPA annotationDefines a many-valued association with one-to-many multiplicity.See JavaDoc Reference Page... annotations:
@Entityjavax.persistence.EntityJPA annotationSpecifies that the class is an entity.See JavaDoc Reference Page... class Employee { : @OneToOnejavax.persistence.OneToOneJPA annotationDefines a single-valued association to another entity that has one-to-one multiplicity.See JavaDoc Reference Page...(orphanRemovalOneToOne.orphanRemovalannotation element(Optional) Whether to apply the remove operation to entities that have been removed from the relationship and to cascade the remove operation to those entities.See JavaDoc Reference Page...=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.
- If
orphanRemoval=true
is specified the disconnectedAddress
instance is automatically removed. This is useful for cleaning up dependent objects (e.g.Address
) that should not exist without a reference from an owner object (e.g.Employee
). - If only
cascade=CascadeType.REMOVE
is specified no automatic action is taken since disconnecting a relationship is not a remove operation.
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:
@Entityjavax.persistence.EntityJPA annotationSpecifies that the class is an entity.See JavaDoc Reference Page... class Employee { : @OneToManyjavax.persistence.OneToManyJPA annotationDefines a many-valued association with one-to-many multiplicity.See JavaDoc Reference Page...(orphanRemovalOneToMany.orphanRemovalannotation element(Optional) Whether to apply the remove operation to entities that have been removed from the relationship and to cascade the remove operation to those entities.See JavaDoc Reference Page...=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.
DELETE Queries
DELETE queries provide an alternative way for removing entity objects from the database. Deleting objects using a DELETE query may be useful especially when many entity objects have to be deleted in one operation. The DELETE Queries in JPA/JPQL in chapter 4 explains how to use JPA DELETE queries.