Cascading persist, merge and remove
When persisting or removing entity, all your references are by default cascade persisted. This means that by persisting any entity, ORM will automatically persist all of its associations.
You can control this behaviour via cascade
attribute of @ManyToOne
, @ManyToMany
,
@OneToMany
and @OneToOne
fields.
New entities without primary key will be always persisted, regardless of
cascade
value.
#
Cascade persistHere is example of how cascade persist works:
When cascade persisting collections, keep in mind only fully initialized collections will be cascade persisted.
#
Cascade mergeWhen you want to merge entity and all its associations, you can use Cascade.MERGE
. This
comes handy when you want to clear identity map (e.g. when importing large number of entities),
but you also have to keep your parent entities managed (because otherwise they would be considered
as new entities and insert-persisted, which would fail with non-unique identifier).
In following example, without having Author.favouriteBook
set to cascade merge, you would
get an error because it would be cascade-inserted with already taken ID.
#
Cascade removeCascade remove works same way as cascade persist, just for removing entities. Following
example assumes that Book.publisher
is set to Cascade.REMOVE
:
Note that cascade remove for collections can be inefficient as it will fire 1 query for each entity in collection.
Keep in mind that cascade remove can be dangerous when used on @ManyToOne
fields,
as cascade removed entity can stay referenced in another entities that were not removed.
#
Orphan removalIn addition to Cascade.REMOVE
, there is also additional and more aggressive remove
cascading mode which can be specified using the orphanRemoval
flag of the @OneToOne
and @OneToMany
properties:
orphanRemoval
flag behaves just likeCascade.REMOVE
for remove operation, so specifying both is redundant.
With simple Cascade.REMOVE
, you would need to remove the Author
entity to cascade
the operation down to all loaded Book
s. By enabling orphan removal on the collection,
Book
s will be also removed when they get disconnected from the collection (either via
remove()
, or by replacing collection items via set()
):
In this example, no Book
would be removed with simple Cascade.REMOVE
as no remove operation
was executed.
#
Declarative Referential IntegrityThis is only supported in SQL drivers.
As opposed to the application level cascading controlled by the cascade
option, we can
also define database level referential integrity actions: on update
and on delete
.
Their values are automatically inferred from the cascade
option value. You can also
control the value manually via onUpdateIntegrity
and onDelete
options.