菜鸟学习Hibernate——一对多关系映射
最后更新于:2022-04-01 09:33:50
Hibernate中的关系映射,最常见的关系映射之一就是一对多关系映射例如学生与班级的关系,一个班级对应多个学生。如图:
![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-02-22_56caddfaefcf5.jpg)
Hibernate中如何来映射这两个的关系呢?
下面就为大家讲解一下:
1、创建实体类Classes和实体类Student
Classes.java
~~~
package com.bjpowernode.hibernate;
import java.util.Set;
public class Classes {
private int id;
private String name;
private Set students;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set getStudents() {
return students;
}
public void setStudents(Set students) {
this.students = students;
}
}
~~~
Student.java
~~~
package com.bjpowernode.hibernate;
public class Student {
private int id;
private String name;
private Classes classes;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Classes getClasses() {
return classes;
}
public void setClasses(Classes classes) {
this.classes = classes;
}
}
~~~
2、创建映射文件Classes.hbm.xml和Student.hbm.xml
Classes.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.bjpowernode.hibernate.Classes" table="t_classes">
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
<set name="students" inverse="true">
<!--
<key column="classesid" not-null="true"/>
-->
<key column="classesid"/>
<one-to-many class="com.bjpowernode.hibernate.Student"/>
</set>
</class>
</hibernate-mapping>
~~~
Student.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.bjpowernode.hibernate.Student" table="t_student">
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
<many-to-one name="classes" column="classesid"/>
</class>
</hibernate-mapping>
~~~
3、效果图
![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-02-22_56caddfb09675.jpg)
PS:我上面举例的是一对多双向关联的例子。有双向关联当然就有单向关联。下面举个例子来说明他们的区别
如果Student添加了一条记录当中的classesid在Classes中没有这个id,双向关联的话则先添加学生这条记录然后再班级那里添加这个班级,然后再更新学生的classesid。单向关联的话先添加班级,然后再添加学生。