多对一(单向)
Student(多) Teacher(一)
Student类中加入Teacher get,set等,在Stuent.hbm.xml配置文件中:
<many-to-one name="teacher" column="teacher_id" class="hibernate.bean.Teacher" fetch="select" lazy="false" cascade="save-update"></many-to-one>
Student student = new Student();
student.setId(new Integer(5));
student.setName("小sf");
student.setAge(new Integer(18));
Teacher teacher = new Teacher();
teacher.setId(1);
teacher.setTeacherName("张老师");
student.setTeacher(teacher);
级联更新
查询时:会自动从数据库中读取对应是Teacher信息
List<Student> list = (List<Student>)session.createQuery("from Student").list();
for(int i = 0; i < list.size(); i++)
{System.out.print("\n学生名:" + list.get(i).getName());
if(list.get(i).getTeacher() != null) System.err.print("" + list.get(i).getTeacher().getTeacherName());}
一对多(双向)
Teacher(一) Student(多)
Teacher类中:private Set students = null; get set方法
Teacher.hmb.xml
<set name="students" inverse="true" fetch="select" cascade="save-update" lazy="true">
<key column="teacher_id"></key><one-to-many class="hibernate.bean.Student"/> </set>
student不需加任何东西(只要自己的就可以了)因为是单项的,等下看下双向如何:
测试:
Teacher teacher = new Teacher();
teacher.setId(3);
teacher.setTeacherName("王老师");
Student student1 = new Student();
student1.setId(6);
student1.setName("王一");
Student student2 = new Student();
student2.setId(7);
student2.setName("王一");
Set<Student> set = new HashSet<Student>();
set.add(student1);
set.add(student2);
teacher.setStudents(set);
session.save(teacher);
一对多双向关联
student有Teacher变量,配置文件中有Many-to-on
Teacher有set和配置文件中的<set 配置,
Set set = new HashSet();
Teacher teacher = new Teacher();
teacher.setId(10);
Student student = new Student();
student.setId(10);
set.add(student);
teacher.setStudents(set);
session.save(teacher);
Student d = new Student();
d.setId(12);
d.setTeacher(teacher);
如果教师表没有指定save-update,则无法保存student对象,而Teacher类的Inverse为True,所以student的teacher_id为NUll,因此要从多对一的一方插入,而删除是,Teacher的级联设定为delete则从一的一方删除。
两方不能同时指定为save-update
多对多(双向)
借助第三方表student_teacher
Teacher类中有Set <STUDENT> Student中有set <Teacher>
student.hbm.xml:
<set name="teacher" table="student_teacher" lazy="true" cascade="save-update" inverse="true">
<key column="student_id"></key> <many-to-many class="Teacher" column="teacher_id"></many-to-many> </set>
Teacher
<set name="students" fetch="select" cascade="save-update" lazy="false" table="student_teacher">
<key column="teacher_id"></key>
<many-to-many class="hibernate.bean.Student" column="student_id"/>
</set>
注意在多对多中,必须有一个映射关联为 Insverse= true