---
title: "hibernate 的关系映射(配置实例)"
author: "birch"
date: "2008-09-25T09:43:08Z"
tags: []
slug: "hibernate"
draft: false
lastmod: "2008-09-25T09:43:08Z"
id: 246550
url: "https://birch.iteye.com/blog/246550"
---

今天想结合自己所做的例子,来介绍一下在struts2+hibernate+spring的整合下,如何配置hibernate的关系映射的映射文件.

    关系映射有几种情况,分别是单向N-1(多对一)的关系映射,单向1-1(一对一)的关系映射,单向1-N(一对多)的关系映射,单向N-N(多对多)的关系映射,还有双向1-N(一对多)的关系映射,双向N-N(多对多)的关系映射以及双向1-1(一对一)的关系映射.

下面结合实例来分析一下单向一对一和双向一对多的关系映射:

以下只列出三张数据库表来分析,如下:


一、会员信息表（userinfo）
字段名称	           逻辑意义	       格式	约束条件
ui_ID	         会员编号	        int	主键
ui_nick	          登录名	      Varchar(20)	not null
ui_Sex             性别             boolean      默认true
ui_Password	 密码	      Varchar(20)	not null
ui_Integral	 积分	        int(11)	默认0
ui_level	          级别              int(2)	1:管理员2.站长3.vip 4.会员
ui_COID            学校ID           int(11)     外键

二、商店信息表（shopinfo）
字段名称	            逻辑意义	       格式	  约束条件
si_UID	          商店编号	        Int	  主键也是外键(UIID)
si_Address	 店铺地址	    Varchar(20)	   not null
si_Name	          店铺名称	     Varchar(20)	   not null
Si_describe	 店铺描述	     Varchar(4000)    not null
Si_Date	          开店日期	      dateTime        not null
si_InSchool	是否学校推荐     boolean	   默认False
si_IsInHead	是否首页推荐     Boolean	   默认False
si_Fsore	是        否为专卖店	      Boolean	   默认False

三、学校表(college)
字段名称	          逻辑意义	        格式	      约束条件
co_ID	         学校编号	        Int	      主键
co_Name	         学校名称	    Varchar(20)	       唯一
co_Logo	         学校图标	     Varchar(50)	     not null

以上的三个表的关系是这样的:
(1)一个会员(userinfo 表)只能申请一间店铺(shopinfo 表),即会员实体与店铺实体  之间存在一对一的关系,并且这里用的是单向的一对一的关系映射,因为shopinf(si_UID)  主键是userinfo的外键(也就是说,会员表的主键也在店铺表里做主键,但是有先后顺序,因此只有注册了会员才能申请店铺),而且我只需要单向地通过会员表的主键(ui_ID)去查询对应的店铺信息即可,而不需要反过来查询.
(2)一间学校(college 表)拥有多个学生(即会员userinfo 表),一个学生就读一间学校,所以学校实体与学生实体之间存在一对多的关系,并且这里用的是双向的一对多的关系映射,因为这里需要双向查询.在这种一对多的实体关系里,我们应该将关系为一的一方的ID(即学校ID)放到多的一方(即会员)的表里进行外键的关联..
(3)一间学校(college 表)管理多间店铺,一间店铺属于一间学校.这里与上面第二点一样,也是双向一对多的关系映射,原因同理.(不过这里大家可以不让学校与店铺直接关联,而是通过会员表为中间表进行间接的关联,也可以使得三个实体之间联成一个整体,不过可能在查询效率上会慢一些.)

下面是model层的三个实体类(实体类的定义是根据上面分析的三个表的实体之间的关系和表所拥有的属性来设计的):
1.userinfo表的实体

package com.flybaba.model;
import java.util.HashSet;
import java.util.Set;

public class UserInfo implements java.io.Serializable {

	private Integer uiID;
	private String uiNick;
	private String uiPassword;
	private Integer uiIntegral;
	private Integer uiLevel;
	private College college;

	public String getUiNick() {
		return uiNick;
	}

	public void setUiNick(String uiNick) {
		this.uiNick = uiNick;
	}

	public String getUiPassword() {
		return uiPassword;
	}

	public void setUiPassword(String uiPassword) {
		this.uiPassword = uiPassword;
	}

	public Integer getUiIntegral() {
		return uiIntegral;
	}

	public void setUiIntegral(Integer uiIntegral) {
		this.uiIntegral = uiIntegral;
	}

	public Integer getUiLevel() {
		return uiLevel;
	}

	public void setUiLevel(Integer uiLevel) {
		this.uiLevel = uiLevel;
	}

	public boolean isUiSex() {
		return uiSex;
	}

	public void setUiSex(boolean uiSex) {
		this.uiSex = uiSex;
	}

	public College getCollege() {
		return college;
	}

	public void setCollege(College college) {
		this.college = college;
	}
	
	public Integer getUiID() {
		return uiID;
	}

	public void setUiID(Integer uiID) {
		this.uiID = uiID;
	}

}


2.shopinfo表的实体
package com.flybaba.model;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

public class ShopInfo implements java.io.Serializable {

	private Integer siUID;
	private String siAddress;
	private String siName;
	private String siDescribe;
	private Date siDate;
	private boolean siIsInSchool;
	private boolean siIsInHead;
	private boolean siFsore;
	private College college;
	private UserInfo userInfo;

	public String getSiAddress() {
		return siAddress;
	}

	public void setSiAddress(String siAddress) {
		this.siAddress = siAddress;
	}

	public String getSiName() {
		return siName;
	}

	public void setSiName(String siName) {
		this.siName = siName;
	}

	public String getSiDescribe() {
		return siDescribe;
	}

	public void setSiDescribe(String siDescribe) {
		this.siDescribe = siDescribe;
	}

	public Integer getSiHonor() {
		return siHonor;
	}

	public void setSiHonor(Integer siHonor) {
		this.siHonor = siHonor;
	}

	public Date getSiDate() {
		return siDate;
	}

	public void setSiDate(Date siDate) {
		this.siDate = siDate;
	}

	public College getCollege() {
		return college;
	}

	public void setCollege(College college) {
		this.college = college;
	}

	public boolean isSiIsInSchool() {
		return siIsInSchool;
	}

	public void setSiIsInSchool(boolean siIsInSchool) {
		this.siIsInSchool = siIsInSchool;
	}

	public boolean isSiIsInHead() {
		return siIsInHead;
	}

	public void setSiIsInHead(boolean siIsInHead) {
		this.siIsInHead = siIsInHead;
	}

	public boolean isSiFsore() {
		return siFsore;
	}

	public void setSiFsore(boolean siFsore) {
		this.siFsore = siFsore;
	}

	public UserInfo getUserInfo() {
		return userInfo;
	}

	public void setUserInfo(UserInfo userInfo) {
		this.userInfo = userInfo;
	}

	public Integer getSiUID() {
		return siUID;
	}

	public void setSiUID(Integer siUID) {
		this.siUID = siUID;
	}

}

3.college表的实体
package com.flybaba.model;
import java.util.HashSet;
import java.util.Set;

public class College implements java.io.Serializable {

	private Integer coID;
	private String coName;
	private String coLogo;
	private Set<ShopInfo> shopInfoSet = new HashSet<ShopInfo>();
	private Set<UserInfo> userInfoSet = new HashSet<UserInfo>();

	public Integer getCoID() {
		return coID;
	}

	public void setCoID(Integer coID) {
		this.coID = coID;
	}

	public String getCoName() {
		return coName;
	}

	public void setCoName(String coName) {
		this.coName = coName;
	}

	public String getCoLogo() {
		return coLogo;
	}

	public void setCoLogo(String coLogo) {
		this.coLogo = coLogo;
	}

	public Set<ShopInfo> getShopInfoSet() {
		return shopInfoSet;
	}

	public void setShopInfoSet(Set<ShopInfo> shopInfoSet) {
		this.shopInfoSet = shopInfoSet;
	}

	public Set<UserInfo> getUserInfoSet() {
		return userInfoSet;
	}

	public void setUserInfoSet(Set<UserInfo> userInfoSet) {
		this.userInfoSet = userInfoSet;
	}
}

下面是来配置上面的单向一对一和双向一对多的关系映射的映射文件
(关系映射的映射文件设计是参照上面定义的model层的三个实体类),如下:
一.
1.映射文件名:UserInfo.hbm.xml
2.映射文件内容如下:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >

<hibernate-mapping package="com.flybaba.model">
  <class name="UserInfo" table="userinfo">
    <id name="uiID" type="integer" column="ui_ID">
     <generator class="increment" />
    </id>
   <property name="uiNick" column="ui_Nick" type="string"
             not-null="true" length="20" />
   <property name="uiPassword" column="ui_Password" type="string"
	    not-null="true" length="30" />
   <property name="uiIntegral" column="ui_Integral" type="integer"
	    not-null="false" length="30" />
   <property name="uiLevel" column="ui_Level" type="integer"
	    not-null="false" length="2" />
   <property name="uiSex" column="ui_Sex" type="boolean"
	    not-null="true" length="2" /> 
   <many-to-one name="college" column="ui_COID" class="College"
	    not-null="true" lazy="false" />
   </class>
</hibernate-mapping>

二.
1.映射文件名:ShopInfo.hbm.xml
2.映射文件内容如下:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >

<hibernate-mapping package="com.flybaba.model">
  <class name="ShopInfo" table="shopinfo" >
    <id	name="siUID" type="integer" column="si_UID"	>
     <generator class="foreign">
      <param name="property">userInfo</param>
     </generator>
    </id>
    <property name="siAddress" column="si_Address" type="string" not-              null="true" length="100"/>
    <property name="siName" column="si_Name" type="string" not-              null="true" length="30"/>
    <property name="siDescribe" column="si_Describe" type="string"    not-null="true" length="2048"/>
    <property name="siHonor" column="si_Honor" type="integer" not- null="true" length="9"/>
    <property name="siDate" column="si_Date" type="date" not-null="true" length="20"/>
     <property name="siIsInSchool" column="si_IsInSchool"  type="java.lang.Boolean" not-null="true" length="2"/>
     <property name="siIsInHead" column="si_IsInHead" type="java.lang.Boolean" not-null="true" length="2"/>
     <property name="siFsore" column="si_Fsore" type="java.lang.Boolean" not-null="true" length="2"/>
     <many-to-one name="college" column="si_COID" class="College" not-null="true" lazy="false"/>
    <one-to-one name="userInfo" constrained="true"/>
	</class>	
</hibernate-mapping>

三.
1.映射文件名:College.hbm.xml
2.映射文件内容如下:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >

<hibernate-mapping package="com.flybaba.model">
  <class	name="College" table="college" >
    <id	name="coID" type="integer" column="co_ID">
      <generator class="increment"/>
    </id>
    <property name="coName" column="co_Name" type="string" not- null="true" length="20"/>
    <property name="coLogo" column="co_Logo" type="string" not- null="true"	length="50"/>
 		
   <set name="shopInfoSet" inverse="true">
     <key column="si_COID"/>
        <one-to-many class="ShopInfo" />
     </set>
     <set name="userInfoSet" inverse="true">
	<key column="ui_COID"/>
         <one-to-many class="UserInfo" />
     </set>			
  </class>	
</hibernate-mapping>

到此为止,配置完成.