然后是映射文件:
重要的是这个地方:
<generator class="foreign">
<param name="property">student</param>
</generator>
表示IdCard的id是根据student的id生成的。 generator就是定义id的生成方式。 param是定义有那个属性,即student来确定id.
- <hibernate-mapping>
- <class name="modle.IdCard" table="idcard" catalog="h_01">
- <id name="id" type="int">
- <generator class="foreign">
- <param name="property">student</param>
- </generator>
- </id>
- <property name="num" type="int"></property>
- <one-to-one name="student" class="modle.Student" fetch="select" ></one-to-one>
- </class>
- </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>
注意:两个配置文件都要修改!
这下查询就变成了:
- Hibernate: select student0_.id as id3_0_, student0_.name as name3_0_ from h_01.student student0_ where student0_.id=?
- 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配置设置为级联的。
