Hibernate Inverse attribute

这一生的挚爱 提交于 2019-12-04 08:38:56

问题


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();
  • Q1) If the parent owns the relationship, as in , for the parent inverse=false, then would the child element addition be updated in teh database?
  • Q2) If the child owns the relationship, as in , for the parent inverse=true, then will the child element addtion be updated in the databse?
  • Q3) Who owns the relationahsip does not make a difference in the above code in terms of whether the updaet will be seen or not?

thanks a lot


回答1:


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.




回答2:


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.




回答3:


If we are using inverse=true, means the child is responsible to update relation ship. Compulsory child object should contain the parent object else foreign key is not updated.




回答4:


In a parent child relation ship between two different entities,

e.g one to many(1:N) or many to one(N:1)

Parent <-> Child. (Owner) (Inverse)

If parent is owner then child is its inverse.

Using the inverse is always check for child.

By default we always consider from parent side. So by default inverse = false means parent is owner.

If inverse= true then child is owner. So persisting of entity will always take from owner side.



来源:https://stackoverflow.com/questions/6423889/hibernate-inverse-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!