老师可以查看自己的学生,学生也可以查看自己的老师:
老师Teacher类:
package com.oracle.hibernate;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
public class Teacher {
private int id;
private String name;
//用set集合,不重复。因为表里的记录也不会重复
private Set<Student> students = new HashSet<Student>();
@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
/**
*会生成一张中间表,默认名字为Teacher_student,
* 默认的列名为teacher_id,students_id,
* @JoinTable修改中间表名、属性名
* name="t_s" 指定中间表名字
* 中间表只有学生id和老师id,
* joinColumns指定当前(Teacher类)的表的id
* inverseJoinColumns,逆转的,对方的,指定对方那张表对应的外键的id
*/
@ManyToMany
@JoinTable(name="t_s",
joinColumns={@JoinColumn(name="teacher_id")},
inverseJoinColumns={@JoinColumn(name="student_id")}
)
public Set<Student> getStudents() {
return students;
}
public void setStudents(Set<Student> students) {
this.students = students;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Student类:
package com.oracle.hibernate;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
@Entity
public class Student {
private int id;
private String name;
private Set<Teacher> teachers = new HashSet<Teacher>();
//
@ManyToMany(mappedBy="students")
public Set<Teacher> getTeachers() {
return teachers;
}
public void setTeachers(Set<Teacher> teachers) {
this.teachers = teachers;
}
@Id
@GeneratedValue
public 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;
}
}
生成的表和多对一单向一样:
生成表语句:
create table Student (
id integer not null auto_increment,
name varchar(255),
primary key (id)
)
create table Teacher (
id integer not null auto_increment,
name varchar(255),
primary key (id)
)
create table t_s (
teacher_id integer not null,
student_id integer not null,
primary key (teacher_id, student_id)
)
alter table t_s
add index FK1BF68372EF01B (teacher_id),
add constraint FK1BF68372EF01B
foreign key (teacher_id)
references Teacher (id)
alter table t_s
add index FK1BF682693A57B (student_id),
add constraint FK1BF682693A57B
foreign key (student_id)
references Student (id)