关联关系映射之一对多
程序员文章站
2022-04-20 11:13:36
...
关联关系映射
一对多关联关系:
一对多关联关系是比较常用的关系之一比如:
留言和回复、班级和学生、类别和商品 都是典型的一对多关联关系。在数据库表中的一对多关联关系主要通过外键来建立两表之间的关系
在Hibernate的关联中,添加关联属性,如本例所示,应该在Grade类中添加Set类型的students属性实现和Student之间的一对多单向关联关系
package com.zx.model; public class Student { private int studentID; private String studentName; public int getStudentID() { return studentID; } public void setStudentID(int studentID) { this.studentID = studentID; } public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } } package com.zx.model; import java.util.HashSet; import java.util.Set; public class Grade { private int gradeID; private String gradeName; private String gradeDesc; private Set<Student> students = new HashSet<Student>(); public int getGradeID() { return gradeID; } public void setGradeID(int gradeID) { this.gradeID = gradeID; } public String getGradeName() { return gradeName; } public void setGradeName(String gradeName) { this.gradeName = gradeName; } public String getGradeDesc() { return gradeDesc; } public void setGradeDesc(String gradeDesc) { this.gradeDesc = gradeDesc; } public Set<Student> getStudents() { return students; } public void setStudents(Set<Student> students) { this.students = students; } }
然后在关联映射文件Grade.hbm.xml中为刚刚添加的集合属性students建立映射信息,如下:
<hibernate-mapping package="com.zx.model"> <class name="Grade" table="grade"> <id name="gradeID" column="gradeID" type="integer"> <generator class="native" /> </id> <property name="gradeName" type="string" column="gradeName" /> <property name="gradeDesc" type="string" column="gradeDesc" /> <set name="students" lazy="false"> <key column="gradeID" /> <one-to-many class="com.zx.model.Student"/> </set> </class> </hibernate-mapping>
key : 指定的关联表中的外键,也就是说这里指的是 Student表中的外键 GradeID
one-to-many : 指的是关联类型为com.demo.Student类
测试:
public static void main(String[] args) { Configuration configuration = new Configuration().configure(); SessionFactory sessionFactory = configuration.buildSessionFactory(); Session session = sessionFactory.openSession(); Grade g = (Grade)session.get(Grade.class, 1); Iterator<Student> it = g.getStudents().iterator(); while(it.hasNext()){ Student s = it.next(); System.out.println(g.getGradeName() + ":" + s.getStudentName()); } }