17。多:多映射
1.数据库中,使用中间表完成多:多关联。
2.类图中,单向导航,在”导航“类中使用@ManyToMany即可。
3.双向导航:分别在导航类中使用@ManyToMany,并选择其中一个使用(mappedBy)或@Transient
单向例子:student和teacher。
需求:student可以找到教他的所有老师。而老师不必找到他教的学生。
Student.java
@Entity @Table(name = "t_student") public class Student { private Set<Teacher> teacher = new HashSet<Teacher>(); private int id; private String name; @ManyToMany //设置中间表的列名 @JoinTable(name = "s_t", joinColumns = { @JoinColumn(name = "studentID") }, inverseJoinColumns = { @JoinColumn(name = "teacherID") }) public Set<Teacher> getTeacher() { return teacher; } @Id @GeneratedValue public int getId() { return id; }
Teacher表不需要导航到Student,自然就不用标注任何注解了。
但是,如果Teacher类需要导航到Student,那么就要在Teacher中加注解:@transient或者@ManyToMany(mappedBy=”teacher”);
@Entity @Table(name="t_teacher") public class Teacher { private int id; private String name; private Set<Student> student = new HashSet<Student>(); @Id @GeneratedValue public int getId() { return id; } public String getName() { return name; } //@Transient @ManyToMany(mappedBy="teacher") public Set<Student> getStudent() { return student; }