I am creating a one-to-many relationship. so, i have a parent and a child. The cascade attribute is set to all.
I was wondering, if we consider the following piece of code:
Parent p = (Parent) session.load(Parent.class, pid);
Child c = new Child("child element");
p.addChild(c);
session.flush();
thanks a lot
inverse="true" basically means that the inverse relationship is also mapped within the class definition of the other class. But, it's real meaning is that it defines which side is the parent or the relationship owner for the two entities (parent or child).
In Hibernate, only the “relationship owner” should maintain the relationship, and the “inverse” keyword is created to defines which side is the owner to maintain the relationship. However the “inverse” keyword itself is not verbose enough, I would suggest change the keyword to “relationship_owner“.
The inverse equals true tells NHibernate which side of the relationship to ignore. When you apply it to the collection side and NHibernate will always update the foreign key from the other side, from the child object side.
To use lazy collection, you may optionally use lazy="true" attribute in your collection. It is by default true, so you don't need to do this. If you set it to false, all the child objects will be loaded initially which will decrease performance in case of big data.
Case inverse = false:
In this case, it is parent's responsibility to save-update child and its relationship. So in your example, child will be updated in database. There will be two sql queries: 1) Insert child. 2) Update child with foreign key of parent id.
Case Inverse = true:
In this case , it is child's responsibility to save-update itself. So in your code, child will be saved in database but foreign key of parent will be null. Only one sql query will be executed and that is of insert child. For updating parent's foreign key, you need to manually save child.
Child child = new Child();
child.setParent(parent);
session.save(child);
I think, answer of these cases explains answer of your third question.
Hope this help.
Inverse is only to tell NH that the foreign key is mapped twice, usually as a one-to-many and a many-to-one, and that it therefore only needs to be stored from one side.
Q1) the child is stored by cascade, but the parent-FK is null. (Except you set the parent relation in the child within p.addChild(c)
.)
Q2) same as Q1.
Q3) exactly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With