Hibernate一对多多对一的相关配置和操作
一对多和多对一之间的操作
拿简单的我们最常见的例子去举例:一个老师可以有多个学生,但是一个学生只能对应一个老师,那么老师就是多的一方,学生就是少的一方
先看下实体类吧:
我们在多方配置一个属性把学生配置到一个set集合里面,在一方配置Teacher属性,
配置文件:
这个是多方的配置文件
这个是一方的配置文件
级联操作这个配置一般不建议配置,目的是为了简化代码,少写两行代码,一般使用的是save-update,delete有风险
=========================测试代码===========================
package TestOne2many;
import java.util.HashSet;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import Bean.Student;
import Bean.Teacher;
import common.HibernateUitels;
public class Testadd {
@Test
public void tests() {
Session session=HibernateUitels.getSession();
Transaction tx = session.beginTransaction();
Teacher teacher=new Teacher();
teacher.setName("401");
Student a1=new Student();
a1.setName("k22");
Student a2=new Student();
a2.setName("hh4");
Set<Student> students =new HashSet<Student>();
students.add(a1);
students.add(a2);
teacher.setStudents(students);
a1.setTeacher(teacher);
a2.setTeacher(teacher);
session.save(teacher);
// session.save(a1);
// session.save(a2);
tx.commit();
}
@Test
//位学生增加老师
public void testadd1() {
Session session=HibernateUitels.getSession();
Transaction tx = session.beginTransaction();
Teacher teacher = session.get(Teacher.class, 1);
Student student=new Student();
student.setName("6969");
student.setTeacher(teacher);
session.save(student);
tx.commit();
}
@Test
//得到老师所教的学生
public void se() {
Session session=HibernateUitels.getSession();
Transaction tx = session.beginTransaction();
Teacher teacher = session.get(Teacher.class,1);
Set<Student> students = teacher.getStudents();
System.out.println(students.size());
tx.commit();
}
@Test
//为学生删除老师
public void testdelete() {
Session session=HibernateUitels.getSession();
Transaction tx = session.beginTransaction();
Student student = session.get(Student.class,1);
student.setTeacher(null);
tx.commit();
}
}
=======================补充=============