关联关系映射之一对多

阅读更多

关联关系映射

一对多关联关系:

一对多关联关系是比较常用的关系之一比如:

留言和回复、班级和学生、类别和商品 都是典型的一对多关联关系。在数据库表中的一对多关联关系主要通过外键来建立两表之间的关系
关联关系映射之一对多_第1张图片
 在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 students = new HashSet();

	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 getStudents() {
		return students;
	}

	public void setStudents(Set students) {
		this.students = students;
	}
}

  然后在关联映射文件Grade.hbm.xml中为刚刚添加的集合属性students建立映射信息,如下:


	
		
			
		
		
		
		
			
			
		
	

 

   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 it = g.getStudents().iterator();
		while(it.hasNext()){
			Student s = it.next();
			System.out.println(g.getGradeName() + ":" + s.getStudentName());
		}
	}

 

  • 关联关系映射之一对多_第2张图片
  • 大小: 8.4 KB
  • 查看图片附件

你可能感兴趣的:(hibernate,映射,一对多)