你好,游客 登录 注册 搜索
背景:
阅读新闻

Hibernate 一对一双向关联深入详解

[日期:2012-11-03] 来源:Linux社区  作者:gaotong2055 [字体:大 中 小]

然后是映射文件:

重要的是这个地方:

<generator class="foreign">
                 <param name="property">student</param>
 </generator>

表示IdCard的id是根据student的id生成的。  generator就是定义id的生成方式。 param是定义有那个属性,即student来确定id.

  1. <hibernate-mapping> 
  2.     <class name="modle.IdCard" table="idcard" catalog="h_01"> 
  3.         <id name="id" type="int"> 
  4.             <generator class="foreign"> 
  5.                 <param name="property">student</param> 
  6.             </generator> 
  7.         </id> 
  8.         <property name="num" type="int"></property> 
  9.         <one-to-one name="student" class="modle.Student" fetch="select" ></one-to-one> 
  10.     </class> 
  11. </hibernate-mapping> 

再说下查询:

1、一对一,hibernate默认的是用左外连接查询。

比如,查询一个student, hibernate使用做外连接直接查询除了idcard.


Hibernate: select student0_.id as id3_2_, student0_.name as name3_2_, idcard1_.id as id4_0_, idcard1_.num as num4_0_, student2_.id as id3_1_, student2_.name as name3_1_ from h_01.student student0_ left outer join h_01.idcard idcard1_ on student0_.id=idcard1_.id left outer join h_01.student student2_ on idcard1_.id=student2_.id where student0_.id=?

有事我们并不需要idcard,为了速度  。 可以用延迟加载。
需要修改下查询方式,即fetch属性的配置,默认是join

<one-to-one name="student" class="modle.Student" fetch="select" ></one-to-one> 

注意:两个配置文件都要修改!

这下查询就变成了:

  1. Hibernate: select student0_.id as id3_0_, student0_.name as name3_0_ from h_01.student student0_ where student0_.id=? 
  2. Hibernate: select idcard0_.id as id4_0_, idcard0_.num as num4_0_ from h_01.idcard idcard0_ where idcard0_.id=? 

之所以有两个查询语句,因为我使用了card对象。所以又查询了card

2、默认对student的保存是不级联的。不知道是不是和版本有关。

可以把student配置设置为级联的。

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款