1 单向多对一和单向多对一的区别
比如部门和员工,一个部门下有很多员工,如果只查一个员工属于哪个部门,就用单向的,如果还要查一个部门下的所有员工,就用双向的。
2 双向多对一的配置
除了单向xml和双向xml都配置关联关系之外,java类也要都写一对多和多对一的关联
xml一方:
<set name="students" table="student" inverse="true">
<key column="gid">
</key>
<one-to-many class="com.ddwei.entity.Student"/>
</set>
xml多方:
<many-to-one name="grade" class="com.ddwei.entity.Grade" column="gid"></many-to-one>
java类:
public static void testManyToOne(){
Student stu1 = new Student("小明","男");
Student stu2 = new Student("小红","女");
Grade grad1 = new Grade("java三班","java三班");
stu1.setGrade(grad1);
stu2.setGrade(grad1);
grad1.getStudents().add(stu1);
grad1.getStudents().add(stu2);
Session ses1 = HibernateUtil.getSession();
Transaction tran = ses1.beginTransaction();
ses1.save(stu1);
ses1.save(stu2);
ses1.save(grad1);
tran.commit();
HibernateUtil.closeSession(ses1);
}