多对多的单向关联
一个老师(Teacher)教多个学生(Student),一个学生(Student)可以有多名老师(Teacher),这就是一对一的关系,下面以这个例子为例进行配置:
Annotataion 配置:
Teacher:
1 package com.bjsxt.hibernate; 2 3 import java.util.HashSet; 4 import java.util.Set; 5 6 import javax.persistence.Entity; 7 import javax.persistence.GeneratedValue; 8 import javax.persistence.Id; 9 import javax.persistence.JoinColumn; 10 import javax.persistence.JoinTable; 11 import javax.persistence.ManyToMany; 12 import javax.persistence.Table; 13 14 @Entity 15 @Table(name="t_teacher") 16 public class Teacher { 17 18 private Integer id; 19 20 private String name; 21 22 private Set<Student> students = new HashSet<Student>(); 23 24 @Id 25 @GeneratedValue 26 public Integer getId() { 27 return id; 28 } 29 30 public void setId(Integer id) { 31 this.id = id; 32 } 33 34 public String getName() { 35 return name; 36 } 37 38 public void setName(String name) { 39 this.name = name; 40 } 41 42 @ManyToMany 43 @JoinTable(name="t_s", 44 joinColumns={@JoinColumn(name="teacher_id")}, 45 inverseJoinColumns={@JoinColumn(name="student_id")} 46 ) 47 public Set<Student> getStudents() { 48 return students; 49 } 50 51 public void setStudents(Set<Student> students) { 52 this.students = students; 53 } 54 55 }
Student:
1 package com.bjsxt.hibernate; 2 3 import javax.persistence.Entity; 4 import javax.persistence.GeneratedValue; 5 import javax.persistence.Id; 6 import javax.persistence.Table; 7 8 @Entity 9 @Table(name="t_student") 10 public class Student { 11 private Integer id; 12 13 private String name; 14 15 @Id 16 @GeneratedValue 17 public Integer getId() { 18 return id; 19 } 20 21 public void setId(Integer id) { 22 this.id = id; 23 } 24 25 public String getName() { 26 return name; 27 } 28 29 public void setName(String name) { 30 this.name = name; 31 } 32 }
XML 配置:
Teacher.hbm.xml
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.bjsxt.hibernate"> <class name="Teacher" table="t_teacher"> <id name="id" column="id"> <generator class="native"/> </id> <property name="name" column="name" /> <set name="students" table="t_s"> <key column="teacher_id"></key><!-- 指定自己这张表在中间表的列名 --> <many-to-many class="Student" column="student_id" /><!-- 指定多对多的那张表在中间表的列名 --> </set> </class> </hibernate-mapping>
Student.hbm.xml
1 <?xml version="1.0"?> 2 <!DOCTYPE hibernate-mapping PUBLIC 3 "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 4 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 5 6 <hibernate-mapping package="com.bjsxt.hibernate"> 7 <class name="Student" table="t_student"> 8 <id name="id" column="id"> 9 <generator class="native"/> 10 </id> 11 <property name="name" column="name" /> 12 </class> 13 </hibernate-mapping>
上面两种方式,生成SQL的结果一样,生成顺序:
jar链接: https://pan.baidu.com/s/1eSKKZ8Q 密码: puad
代码链接: https://pan.baidu.com/s/1bpxk8H5 密码: e7ku