Thursday, May 29, 2014

hiberate cascade on ManyToOne

Normally cascade is put on OneToMany. One is considered as parent and many is considered as children. When parent is saved/updated/.../deleted, if there is cascade set, the same operation will happen on the children.

But hiberante also allows to put the cascade on the ManyToOne side.
Let see what happens if cascade is not set, when the child is going to be saved with a non-persistent parent object.
Here are the domains. DocPackage -> Document is one to many.

Here is the code

Hibernate will throw out this error.

Add cascade

Now run the same test, you can see the parent is inserted before the child is inserted.

What happens if the parent object already exists.

Here are the sql generated by hibernate. After the document is inserted, an update statement is triggered on package.

What happens if we delete the child record
If the document is the only document the package has, two delete statement are executed.

If the docuemnt is not the only document the package has,

All the operations above are triggered from document (the child object). Go back to the parent domain object DocPackage

mappedBy="docPackage" declares the Many side as owner of the relation. mappedBy refers to the property name of the association on the owner side(Document).
If uni-direction mapping, it is like this

Because this is uni-direction and the owner is DocPackage. All operations should be triggered from DocPackage.

No comments:

Post a Comment