ssh学习:hibernate关系映射(2)

hibernate中,单向一对多与多对一的关联关系

1.一对多关联关系

在一对多关系中,只要在少的那一端使用集合封装多的那一端的对象就可以了。

在Xxx.hbm.xml中添加集合的配置标签,在该标签下使用<one-to-many></one-to-many>子表签,并且在子标签中的class属性指定属性类的全路径;

比如set标签中:

 <set name="set属性名"> <key column="外键名"></key> <one-to-many class="封装对象的全路径"/> </set>

 

使用set属性来实现的一对多关联关系实例:

持久化JavaBean实体:

多的一端:

 

public class Order {
			private int id;
			private String orderNum;
			private Date orderTime;
			//省去get/set方法
		}

 

少的一端:

 

public class Account {
			private int id;
			private String accName;
			// 对多端对象集合的引用,可用List,Map,等代替
			private Set<Order> setOrders;
			//省去get/set方法
		}

 

Xxx.hbm.xml配置:

多的一端:

 

<hibernate-mapping>
			<class name="com.usc.geowind.lilin.bean.oneToMany.Order" table="Order">
				<!-- type指明当前字段的类型    name对应实体中的属性名 -->
				<id type="integer" name="id">
					<!-- 提供ID自增的策略  native会根据数据库自行判断 -->
					<generator class="native"/>
				</id>
				<property name="orderNum" type="string"></property>
				<property name="orderTime" type="timestamp"></property>
			</class>
		</hibernate-mapping>

 

少的一端:

 

<hibernate-mapping>
			<class name="com.usc.geowind.lilin.bean.oneToMany.Account" table="Account">
				<!-- type指明当前字段的类型    name对应实体中的属性名 -->
				<id type="integer" name="id">
					<!-- 提供ID自增的策略  native会根据数据库自行判断 -->
					<generator class="native"/>
				</id>
				<property name="accName" type="string"></property>
				<set name="setOrders">
					<!--外键名-->
					<key column="acc_id"></key>
					<!--一对多的标签 class为一对多中多的那一端的是一类,值为全路径 -->
					<one-to-many class="com.usc.geowind.lilin.bean.oneToMany.Order"/>
				</set>
			</class>
		</hibernate-mapping>

 

 

2.多对一关联关系

在多对一的使用当中,配置与一般的配置只是有那么一点点的不同:

在多的一端引用少的一端的对象

在Xxx.hbm.xml配置中,添加<many-to-one></many-to-one>标签,name值指定为属性名:

实例:

持久化JavaBean实体:

多的一端:

 

public class OrderMTO {
			private int id;
			private String orderNum;
			private AccountMTO account;//多对一中少的一端对象
			//省去get/set方法
		}

 

少的一端:

 

public class AccountMTO {
			private int id;
			private String accName;
			//省去get/set方法
		}

 

Xxx.hbm.xml配置:

多的一端:

 

<hibernate-mapping>
			<class name="com.usc.geowind.lilin.bean.oneToMany.OrderMTO"
				table="OrdersMTO">
				<!-- type指明当前字段的类型 name对应实体中的属性名 -->
				<id type="integer" name="id" column="id">
					<!-- 提供ID自增的策略 native会根据数据库自行判断 -->
					<generator class="native" />
				</id>
				<property name="orderNum" type="string" column="orderNum"></property>
				<!--多对一的标签  name属性名,coliumn外键的名字 -->
				<many-to-one name="account" column="acc_id"></many-to-one>
			</class>
		</hibernate-mapping>

 

少的一端:

 

<hibernate-mapping>
			<class name="com.usc.geowind.lilin.bean.oneToMany.AccountMTO" table="AccountMTO">
				<!-- type指明当前字段的类型    name对应实体中的属性名 -->
				<id type="integer" name="id" column="id">
					<!-- 提供ID自增的策略  native会根据数据库自行判断 -->
					<generator class="native"/>
				</id>
				<property name="accName" type="string" column="accName"></property>
			   
			</class>
		</hibernate-mapping>

 

 

你可能感兴趣的:(ssh学习:hibernate关系映射(2))