一、總體來分有一對一、一對多、多對一、多對多這四種關系。
二、一對一關系
1、單向主鍵
2、單向外鍵
具體需求是Husband實體中保存Wife的引用,得到husband的實體後就可以取得wife實體。且關系是一對一。
Husband實體簡略信息
[java]
- private int id;
- private String name;
- private int age;
- private Wife wife;
Wife實體簡略信息
[java]
- private int id;
- private String name;
現在使用xml構建從husband到wife的一對一關聯,xml中使用的是<many-to-one>標簽,理解的大概是外鍵一般都是保存在多這一方,站在當前實體husband的位置上考慮,即保存引用的這一方,這樣就存在關聯的關系,之後加上加上unique屬性進行限定為一對一的關系。(多對一的特殊情況)
[html]
- <hibernate-mapping>
- <class name="com.akwolf.bean.Husband" table="HUSBAND">
- <id name="id" type="int">
- <column name="ID" />
- <generator class="native" />
- </id>
- <property name="name" type="java.lang.String">
- <column name="NAME" />
- </property>
- <property name="age" type="int">
- <column name="AGE" />
- </property>
- <many-to-one name="wife" class="com.akwolf.bean.Wife" fetch="join" unique="true">
- <column name="WIFE" />
- </many-to-one>
- </class>
- </hibernate-mapping>
Wife.hbm.xml簡要配置。
[html]
- <?xml version="1.0"?>
- <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- <!-- Generated 2011-10-2 22:15:15 by Hibernate Tools 3.4.0.CR1 -->
- <hibernate-mapping>
- <class name="com.akwolf.bean.Wife" table="WIFE">
- <id name="id" type="int">
- <column name="ID" />
- <generator class="native" />
- </id>
- <property name="name" type="java.lang.String">
- <column name="NAME" />
- </property>
- </class>
- </hibernate-mapping>
Annotation雙向必設mappedBy
3、雙向主鍵
4、雙向外鍵
現在在wife添加一個Husband的屬性使其可以找到husband,則需在Wife.hbm.xml中進行配置
[html]
- <hibernate-mapping>
- <class name="com.akwolf.bean.Wife" table="WIFE">
- <id name="id" type="int">
- <column name="ID" />
- <generator class="native" />
- </id>
- <property name="name" type="java.lang.String">
- <column name="NAME" />
- </property>
- <one-to-one name="husband" property-ref="wife"></one-to-one>
- </class>
- </hibernate-mapping>
對於property-ref="wife",就是指明要進行關聯的屬性已經在husband的wife屬性進行關聯了
從wife端查詢husband時,hibernate生成的查詢語句
[java]
- Hibernate:
- select
- wife0_.ID as ID1_1_,
- wife0_.NAME as NAME1_1_,
- husband1_.ID as ID0_0_,
- husband1_.NAME as NAME0_0_,
- husband1_.AGE as AGE0_0_,
- husband1_.WIFE as WIFE0_0_
- from
- WIFE wife0_
- left outer join
- HUSBAND husband1_
- on wife0_.ID=husband1_.WIFE
- where
- wife0_.ID=?