Hibernate Inverse Attribute

I create a one-to-many relationship. therefore I have a parent and a child. The cascade attribute is set to everything.

I was wondering if we look at the following code snippet:

Parent p = (Parent) session.load(Parent.class, pid); Child c = new Child("child element"); p.addChild(c); session.flush(); 
  • Q1) If the parent owner is related, as for the parent inverse = false, will the update of the child be updated in the database?
  • Q2) If the child is related, as for the parent inverse = true, will the update of the child be updated in the database?
  • Q3) Who owns the relationship does not matter in the code above in terms of whether it will be updated or not?

Many thanks

+7
source share
4 answers

Case inverse = false:

In this case, the parental responsibility for maintaining-updating the child element and its relationship. Thus, in your example, the child will be updated in the database. There will be two sql queries: 1) Insert the child. 2) Update the child with the foreign key of the parent identifier.

Case Reverse = True:

In this case, the child is responsible for maintaining and updating. This way, in your code, the child will be stored in the database, but the foreign key of the parent will be zero. Only one sql query is executed that has a child insert. To update the parent foreign key, you need to manually save the child.

 Child child = new Child(); child.setParent(parent); session.save(child); 

I think the answer to these cases explains the answer to your third question.

I hope for this help.

+5
source

The converse is only an indication to NH that the foreign key is displayed twice, usually as one-to-many and many-to-one, and therefore it should be stored on one side only.

Q1), the child is cascaded, but parent-FK is null. (Except that you set the parent relation in the child within p.addChild(c) .)

Q2) the same as Q1.

Q3).

+3
source

If we use inverse = true, then the child is responsible for updating the ship's relationship. The required child must contain the parent, otherwise the foreign key is not updated.

+1
source

In the parent relation of children between two different objects

for example, from one to many (1: N) or from several to one (N: 1)

Parent ↔ Child. (Owner) (Reverse)

If the parent is the owner, then the child is the opposite.

Using inverse always checks for a child.

By default, we always view from the parent side. Thus, by default, inverse = false means that the parent is the owner.

If inverse = true, then child is the owner. Thus, a persistent entity will always be accepted by the owner.

0
source

All Articles