老师(Teacher)知道自己教了哪些学生(Student),学生(Student)也知道教自己的有哪些老师(Teacher)
Annotation 配置:
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 @Entity15 @Table(name="t_teacher")16 public class Teacher {17 18 private Integer id;19 20 private String name;21 22 private Setstudents = new HashSet ();23 24 @Id25 @GeneratedValue26 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 @ManyToMany43 @JoinTable(name="t_s",//中间表的表名44 joinColumns={@JoinColumn(name="teacher_id")},//配置主键在中间表的配置45 inverseJoinColumns={@JoinColumn(name="student_id")}//配置另一张多对多的表的主键在中间表的配置46 )47 public Set getStudents() {48 return students;49 }50 51 public void setStudents(Set students) {52 this.students = students;53 }54 55 }
Student:
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.ManyToMany;10 import javax.persistence.Table;11 12 @Entity13 @Table(name="t_student")14 public class Student {15 private Integer id;16 17 private String name;18 19 private Setteachers = new HashSet ();20 21 @Id22 @GeneratedValue23 public Integer getId() {24 return id;25 }26 27 public void setId(Integer id) {28 this.id = id;29 }30 31 public String getName() {32 return name;33 }34 35 public void setName(String name) {36 this.name = name;37 }38 39 @ManyToMany(mappedBy="students")//以 Teacher 对应的表中,students属性的配置为准40 public Set getTeachers() {41 return teachers;42 }43 44 public void setTeachers(Set teachers) {45 this.teachers = teachers;46 }47 }
XML 配置:
Teacher.hbm.xml
1 2 5 67 8 179 1110 12 13 1614 15
Student.hbm.xml
1 2 5 67 8 179 1110 12 13 1614 15
jar包链接: 密码: 1mw3
代码链接: 密码: v3c8