没有关联关系的一方:
package com.eneitys;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "tb_student")
public class Student {
private int id;
private String stuName;
@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
}
有关联关系的一方:
package com.eneitys;
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.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity
@Table(name = "tb_teacher")
public class Teacher {
private int id;
private String name;
private Set<Student> students = new HashSet<Student>();
@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;
}
@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;
}
}
JoinTable注解:name是指定为两张表建立联系的中间表的表名.
joinColumns是指定为当前这个类所生成的外键名.
inverseJoinColumns是指定为另一个类所生成的外键名.
最后生成的中间表的结构是
teacher_id | student_id |
... | ... |
表名为:t_s
如果没有指定@JoinTable的属性,Hibernate会自动取每个表的名字拼装起来作为中间表的表名,维护方的字段是表名+"_id",
反转方的字段是集合的名字+"_id"
tb_teacher_id | students_id |
... | ... |
表名为:tb_teacher_tb_student