Hibernate逆向属性 [英] Hibernate Inverse attribute

查看:113
本文介绍了Hibernate逆向属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一对多的关系。所以,我有一个父母和一个孩子。 cascade属性设置为全部。



我想知道,如果我们考虑以下代码段:

  Parent p =(Parent)session.load(Parent.class,pid); 
Child c = new Child(child element);
p.addChild(c);
session.flush();




  • Q1)如果父母拥​​有关系, parent inverse = false,那么子元素的添加会在数据库中更新吗?

  • Q2)如果父子拥有关系,如父母的inverse = true,那么将子元素添加在数据库中更新?

  • Q3)谁拥有relationahsip在上述代码中是否会显示updaet是否会被显示?



非常感谢

解决方案

Case inverse = false:

在这种情况下,保存更新子及其关系是父母的责任。所以在你的例子中,孩子会在数据库中更新。将会有两个sql查询:1)插入子项。 2)使用父ID的外键更新孩子。



个案反向= true:



在这种情况下,保存更新本身是孩子的责任。因此,在你的代码中,孩子将被保存在数据库中,但父母的外键将为空。只有一个sql查询将被执行并且是插入子节点。对于更新父项的外键,您需要手动保存子项。

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

我认为,这些案例的答案解释了您的第三个问题的答案。



希望得到这个帮助。

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

解决方案

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.

这篇关于Hibernate逆向属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆