Hibernate 、多表关联映射 - 多对多关系映射(many-to-many)

hibernate.cfg.xml:

<hibernate-configuration>
    <session-factory name="sessionFactory">
    	<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    	<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    	<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=UTF-8</property>
    	<property name="hibernate.connection.username">root</property>
    	<property name="hibernate.connection.password"></property>
    	<property name="hibernate.show_sql">true</property>
    	<property name="hibernate.format_sql">true</property>
    	<property name="hibernate.hbm2ddl.auto">update</property>
    	<mapping resource="cn/hbm/Teacher.hbm.xml" />
    	<mapping resource="cn/hbm/Student.hbm.xml" />
    </session-factory>
</hibernate-configuration>

Teacher:

public class Teacher {

	private Integer id;
	private String name;
	private Set<Student> students;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Set<Student> getStudents() {
		return students;
	}
	public void setStudents(Set<Student> students) {
		this.students = students;
	}
	
}

hbm.xml

<hibernate-mapping package="cn.model">
	<class name="Teacher" table="TEACHER">
		<id name="id" column="ID">
			<generator class="native"></generator>
		</id>
		<property name="name" column="NAME" type="java.lang.String" />
		<set name="students" table="TEACHER_STUDENT">
			<key column="TEACHER_ID" />
			<many-to-many class="Student" column="STUDENT_ID" />
		</set>
	</class> 
</hibernate-mapping>

Student:

public class Student {
	private Integer id;
	private String name;
	private Set<Teacher> teachers;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Set<Teacher> getTeachers() {
		return teachers;
	}
	public void setTeachers(Set<Teacher> teachers) {
		this.teachers = teachers;
	}
	
	
}
hbm.xml:

<hibernate-mapping package="cn.model">
	<class name="Student" table="STUDENT">
		<id name="id" column="ID">
			<generator class="native"></generator>
		</id>
		<property name="name" column="NAME" type="java.lang.String" />
		<set name="teachers" table="TEACHER_STUDENT">
			<key column="STUDENT_ID" />
			<many-to-many class="Teacher" column="TEACHER_ID" />
		</set>
	</class> 
</hibernate-mapping>

测试添加代码:

public void saveTeacherAndStudent(){
		Session session=null;
		Transaction tran=null;
		try{
			
			Teacher t1=new Teacher();
			t1.setName("张老师");
		
			Teacher t2=new Teacher();
			t2.setName("王老师");
			
			Student stu1=new Student();
			stu1.setName("小明");
			
			Student stu2=new Student();
			stu2.setName("小强");
			
			Set<Student> set1=new HashSet<Student>();
			set1.add(stu1);
			set1.add(stu2);
			
			Set<Student> set3=new HashSet<Student>();
			set3.add(stu1);
		
			
			t1.setStudents(set1);
			t2.setStudents(set3);
			
			session=HibernateSessionFactory.getSession();
			tran=session.beginTransaction();
			session.save(t1);
			session.save(t2);
			session.save(stu1);
			session.save(stu2);
			tran.commit();
		}catch(Exception e){
			if(session!=null){
				session.close();
			}
		}
	}

添加完成以后,会看到数居库中多添加了一个TEACHER_STUDENT表,表中有两个字段作为联合主键;多对多关系其实就是两个一多的结合体;




测试查询:

public Teacher getTeacherById(Integer id){
		Session session=null;
		try{
			session=HibernateSessionFactory.getSession();
			return (Teacher)session.get(Teacher.class, id);
		}catch(Exception e){
			if(session!=null){
				session.close();
			}
		}
		
		return null;
	}
	public Student getStudentById(Integer id){
		Session session=null;
		try{
			session=HibernateSessionFactory.getSession();
			return (Student)session.get(Student.class, id);
		}catch(Exception e){
			if(session!=null){
				session.close();
			}
		}
		
		return null;
	}


	@Test
	public void testManytoMany2(){
		Demo demo=new Demo();
		Teacher t=demo.getTeacherById(3);
		System.out.println("老师名字:"+t.getName());
		System.out.println("----有学生:");
		for(Student stu : t.getStudents()){
			System.out.println(stu.getName());
		}
	}


通过老师查询老师下有多少学生的这一操作其实是使用了一个关联查询来实现的。下面的通过学生查老师也是同理:

	@Test
	public void testManytoMany3(){
		Demo demo=new Demo();
		Student stu=demo.getStudentById(3);
		System.out.println("学生名字:"+stu.getName());
		System.out.println("----有老师:");
		for(Teacher t : stu.getTeachers()){
			System.out.println(t.getName());
		}
	}


posted @ 2015-10-26 14:56  Bodi  阅读(270)  评论(0编辑  收藏  举报