多对一:
多方配置:
<hibernate-mapping>
<class name="cn.itcast.a_oneToMany.Order" table="t_order">
<id name="id">
<generator class="native"></generator>
</id>
<property name="name" column="name"></property> //column如果与数据库一致可以省略
<property name="price"></property>
<!--
多的一端的映射
private Customer customer;
* name="":表示对象的属性名称在本实体中
* class="":表示对象的属性名称的实体的全路径
* column="":表示外键列的名称
-->
<many-to-one name="customer" class="xxx.xxx.xxx" column="cid"></many-to-one>
</class>
</hibernate-mapping>
一方配置:<hibernate-mapping>
<class name="cn.itcast.a_oneToMany.Customer" table="t_customer">
<id name="id">
<generator class="native"></generator>
</id>
<property name="name"></property>
<!--
set:一对多的映射:
Set<Order> orders = new HashSet<Order>();
* set name:集合的属性名称
* key column:多的一端的外键列的名称
* one-to-many class:集合中存放的对象的全路径
-->
<set name="orders">
<key column="cid"></key>
<one-to-many class="cn.itcast.a_oneToMany.Order"/>
</set>
</class>
</hibernate-mapping>
类中有set集合,在hbm中就要配置set集合
类中没有set集合,在hbm中就直接配置关系
注意:两个配置文件的外键必须对应!!!!!
<!-- 配置一对多的映射文件 -->
<mapping resource="cn/itcast/a_oneToMany/Customer.hbm.xml"/>
<mapping resource="cn/itcast/a_oneToMany/Order.hbm.xml"/>
多对多:
假设student与course多对多。
student的hbm配置:
<hibernate-mapping>
<class name="cn.b_manyToMany.Student" table="t_student">
<id name="id">
<generator class="native"></generator>
</id>
<property name="name"></property>
<!--
set:配置多对多
private Set<Course> courses = new HashSet<Course>();
* set name:表示集合的属性名称
* table="":表示中间表的名称
* key column="":对应中间表中Studuent对应的外键列的名称
* many-to-many class="":表示集合属性名称对应的实体类型(全路径)
* column="":对应中间表中Course对应的外键列的名称
-->
<set name="courses" table="t_s_c">
<key column="sid"></key>
<many-to-many class="cn.b_manyToMany.Course" column="cid"></many-to-many>
</set>
</class>
</hibernate-mapping>
course的hbm文件配置:
<hibernate-mapping>
<class name="cn.b_manyToMany.Course" table="t_course">
<id name="id">
<generator class="native"></generator>
</id>
<property name="name"></property>
<!--
set:配置多对多
Set<Student> students = new HashSet<Student>();
* set name:表示集合的属性名称
* table="":表示中间表的名称
* key column="":对应中间表中Course对应的外键列的名称
* many-to-many class="":表示集合属性名称对应的实体类型(全路径)
* column="":对应中间表中Student对应的外键列的名称
-->
<set name="students" table="t_s_c">
<key column="cid"></key>
<many-to-many class="cn.b_manyToMany.Student" column="sid"></many-to-many>
</set>
</class>
</hibernate-mapping>