映射:表之间的关联
方法一:主要是set的设置
Order.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.cc.hibernate.entities.Order" table="ORDERS">
<id name="orderId" type="java.lang.Integer">
<column name="ORDER_ID" />
<generator class="native" />
</id>
<property name="orderName" type="java.lang.String">
<column name="ORDER_NAME"/>
</property>
<!-- 映射多对一的关联关系
怎样设置关联关系,以及关联关系怎么设置
-->
<set name="customer" cascade="save-update" inverse="true">
<key column="CUSTOMER_ID"></key>
<one-to-many class="com.cc.hibernate.entities.Customer"/>
</set>
<!-- 映射多对一的关联关系
<many-to-one name="customer" class="Customer" column="CUSTOMER_ID" />-->
</class>
</hibernate-mapping>
Customer.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.cc.hibernate.entities.Customer" table="CUSTOMER">
<id name="customerId" type="java.lang.Integer">
<column name="CUSTOMER_ID" />
<generator class="native" />
</id>
<property name="customerName" type="java.lang.String">
<column name="CUSTOMER_NAME"/>
</property>
</class>
</hibernate-mapping>
实现的效果是可以同时对两张表进行操作
是单向多对一。
单向n-1关联只需从n的一端可以访问1的一端
域模型:从Order到Customer的多对一单向关联需要在Order类中定义一个Customer属性,而在Customer类中无需定义存放Order对象的集合属性
关系数据模型:orders表中的customer_id参照customer表的主键
方法二(只更改order.hbm.xml):
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.cc.hibernate.entities">
<class name="Order" table="ORDERS">
<id name="orderId" type="java.lang.Integer">
<column name="ORDER_ID" />
<generator class="native" />
</id>
<property name="orderName" type="java.lang.String">
<column name="ORDER_NAME"/>
</property>
<!-- 映射多对一的关联关系 -->
<many-to-one name="customer" class="Customer" column="CUSTOMER_ID"></many-to-one>
</class>
</hibernate-mapping>