Hibernate多对多关联

王朝学院·作者佚名  2016-05-29
窄屏简体版  字體: 小  |  中  |  大  |  超大  

Hibernate多对多关联多对多关联:

示例:Teacher和Student,一个Teacher可以教很多student,一个Student也可以被很多teacher教

 

多对多单向关联

Teacher知道自己教了哪些学生,Student不知道教自己的有哪些老师

在Teacher中建(Set集合形式的)Student对象,并添加@ManyToMany注解

1.建Teacher实体类和Student实体类,添加Annotation注解,如下 @Entitypublic class Teacher {PRivate int id;private String name;private Set<Student> students = new HashSet<Student>();@Id@GeneratedValuepublic int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}@ManyToMany//@JoinTable(name="t_s",// joinColumns={@JoinColumn(name="t_id")},// inverseJoinColumns={@JoinColumn(name="s_id")}//)public Set<Student> getStudents() {return students;}public void setStudents(Set<Student> students) {this.students = students;}}

 

@Entitypublic class Student {private int id;private String name;@Id@GeneratedValuepublic int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}}

2.在hibernate.cfg.xml中添加mapping语句

<mapping class="com.hibernate.model.Teacher"/><mapping class="com.hibernate.model.Student"/>

3.建Junit测试类

public class ORMappingTest {@Testpublic void test() {new SchemaExport(new Configuration().configure()).create(true, true);}}

程序至此结束,运行程序,在数据库中生成表teacher、表student以及中间表teacher_student(默认名)。

中间表teacher_student中会自动生成属性名为Teacher_id和students_id的两个外键,

可用@JoinTable注解修改中间表的名字及其属性名,如下:

@ManyToMany@JoinTable(name="t_s", joinColumns={@JoinColumn(name="t_id")}, inverseJoinColumns={@JoinColumn(name="s_id")})public Set<Student> getStudents() {return students;}

这样会在数据库中生成名为t_s的中间表,表中有属性名为t_id和s_id的两个外键。

 

多对多双向关联

Teacher知道自己教了哪些学生,Student也知道教自己的有哪些老师

在Teacher中建(Set集合形式的)Student对象,在Student中建(Set集合形式的)Teacher对象,并添加@ManyToMany注解

1.建Teacher实体类和Student实体类,添加Annotation注解

Teacher类,同上

Student类,如下:

@Entitypublic class Student {private int id;private String name;private Set<Teacher> teachers = new HashSet<Teacher>();@Id@GeneratedValuepublic int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}@ManyToMany(mappedBy="students") //多对多关系public Set<Teacher> getTeachers() {return teachers;}public void setTeachers(Set<Teacher> teachers) {this.teachers = teachers;}}

 

2.在hibernate.cfg.xml中添加mapping语句----同上

3.建Junit测试类----同上

 

程序至此结束,运行程序,在数据库中生成表teacher、表student以及中间表teacher_student(默认名)。

中间表teacher_student中会自动生成属性名为Teacher_id和students_id的两个外键,

可用@JoinTable注解修改中间表的名字及其属性名,

这样会在数据库中生成名为t_s的中间表,表中有属性名为t_id和s_id的两个外键。

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航