hibernate笔记--双向一对多映射方法
前两节写了两个例子,分别是单向多对一的映射和单向一对多的映射,这一节继续以这个例子讲一下双向一对多的映射方法,如下图所示:
很多时候,我们既想从一对端获取多对端的信息,又想从多对端获取一对端的数据,这就是需要双向一对多的映射关系,这也是最常见的表与表的映射关系,在hibernate中应当这样配置:
新建Studnet实体类:
public class Student { private int id; private String name; private String sex; private Grade grade; //get/set方法省略 }
新建Grade实体类:
public class Grade { private int id; private String name; private String teacher; private Set<Student> students=new HashSet<Student>(0); //get/set方法省略 }
当前包下新建Student的映射文件Student.hbm.xml:
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.wang.pojo"> <class name="Student" > <id name="id"> <generator class="native"></generator> </id> <property name="name"></property> <property name="sex"></property> <many-to-one name="grade" class="Grade" column="gradeId" not-null="true"></many-to-one> </class> </hibernate-mapping>
当前包下新建Grade的映射文件Grade.hbm.xml:
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.wang.pojo"> <class name="Grade" > <id name="id"> <generator class="native"></generator> </id> <property name="name"></property> <property name="teacher"></property> <!-- set是一种集合属性,可以配置set,list等,这里是Grade的集合属性 name是属性名称 --> <set name="students"> <!-- key表示外键 column表示外键列名 注意在双向一对多的关系中,一对端即这里的Grade不需要设置notnull="true"--> <key column="gradeId" ></key> <one-to-many class="Student"/> </set> </class> </hibernate-mapping>
将两个映射文件添加到hibernate.cfg.xml中去,新建测试类,测试1:自动生成表结构2:存取数据3:读取数据(分别测试从Student一端读取,以及从grade一段读取):
@Test public void testCreateDB() { Configuration cfg = new Configuration().configure(); SchemaExport se = new SchemaExport(cfg); // 第一个参数是否生成ddl脚本 第二个参数是否执行到数据库 se.create(true, true); } @Test public void testSave() { Session session = HibernateUtil.getSession(); Transaction tx = session.beginTransaction(); // Score s=new Score(2,12,97); // session.save(s); Grade g=new Grade(1, "终极一班", "王大炮"); Student s1=new Student(12, "李云龙", "男", g); Student s2=new Student(13, "赵刚", "男", g); session.save(g); session.save(s1); session.save(s2); tx.commit(); session.close(); } @Test public void testGet() { Session session = HibernateUtil.getSession(); Transaction tx = session.beginTransaction(); //从Grade一端获取数据 Grade g=(Grade)session.get(Grade.class, 1); System.out.println("id="+g.getId()+"name="+g.getName()+"teacher="+g.getTeacher()); Iterator<Student> it = g.getStudents().iterator(); while(it.hasNext()){ Student s=it.next(); System.out.println(s); } //从Student一端获取数据 Student s1=(Student)session.get(Student.class, 1); System.out.println(s1.getName()+"====="+s1.getGrade().getName()); tx.commit(); session.close(); }
总结:在双向一对多的映射关系中,注意一的一端(Grade)配置:<key>标签中不需要指定not-null="true";如果想要在一的一端(Grade)来维护关系,那么在多的一端(Student)不用指定关联列非空.