案例:一对多和多对一是相互的,如班级和学生,班级为一方,学生为多方,以班级为主“一对多”,以学生为主“多对一”,当然也可以是双项的。
一对多单向关联
一对多的单向关联,以一方为主进行配置,多方则不需要配置,即在一方配置多方,因为多方可能有多个数据,所以不能用一个对象表示,可能是多个不同的对象,所以我们采用Set来装载不同的多方对象。
/**
* 班级 多方
* @author wanghao
*/
public class Team {
private int teamId;
private String teamName;
//一方对多方的配置
private Set<Student> students;
get set……
/**
* 学生 一方
* @author wanghao
*/
public class Student {
private int stuId;
private String stuName;
get set……
映射文件:
Student.hbm.xml
<class name="org.pojo.one2many.Student"table="tb_student">
<id name="stuId">
<generator class="sequence">
<param name="sequence">seq_id</param>
</generator>
</id>
<property name="stuName"></property>
</class>
Team.hbm.xml
<class name="org.pojo.one2many.Team"table="tb_team">
<id name="teamId">
<generator class="sequence">
<param name="sequence">seq_id</param>
</generator>
</id>
<property name="teamName"></property>
<set name="students" inverse="true"lazy="true">
<key>
<!– team表示多方的列名,和一方关联的列名 -- >
<column name="team"></column>
</key>
<one-to-many class="org.pojo.one2many.Student"/>
</set>
</class>
测试数据添加
tx.begin();
Team t1 = new Team();
t1.setTeamName("java战队");
Student s1 = new Student();
s1.setStuName("zhangsan");
Student s2 = new Student();
s2.setStuName("lisi");
Set<Student> students = new HashSet<Student>();
students.add(s1);
students.add(s2);
t1.setStudents(students);
session.save(s1);
session.save(s2);
session.save(t1);
tx.commit();
备注: 当inverse不写或者=false时候,hibernate发出3条添加语句和2条更新语句,也就是说在添加多方数据时,并没有添加对一方的引用,而是通过更新来完成引用关系的。
在<set>配置中,把inverse设置为true,SQL语句只发出3条,inverse表示关系之间的由谁来维护。默认为false表示双方各自维护,设为true时,表示关系有对方管理,这里由一方管理
如果采用立即加载:lazy=”false”的时候,fetch=”join”此时lazy将失效。Fetch默认为select。
多对一单向关联
/**
* 学生 多方
* @author wanghao
*/
public class Student {
private int stuId;
private String stuName;
private Team team;
get set……..
/**
* 班级 一方
* @author wanghao
*/
public class Team {
private int teamId;
private String teamName;
get set……
映射文件
Student.hbm.xml
<class name="org.pojo.many2one.Student"table="tb_student">
<id name="stuId">
<generator class="sequence">
<param name="sequence">seq_id</param>
</generator>
</id>
<property name="stuName"></property>
<many-to-one name="team"></many-to-one>
</class>
Team.hbm.xml
<class name="org.pojo.many2one.Team"table="tb_team">
<id name="teamId">
<generator class="sequence">
<param name="sequence">seq_id</param>
</generator>
</id>
<property name="teamName"></property>
</class>