多对多单向,一个学生可以有多个老师,一个老师也可以教多个学生。老师可以找到他的学生,学生找不到教他的老师。
老师类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 javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; @Entity public class Student { private int id; private String name; @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; } }
生成的表:
hibernate生成表的语句:
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)
生成了Student表和Teacher表和中间表 t_s,列名也和自己设置的一样。