双向关联 在认为的 主表 上用到 @JoinTable
package com.hibernate.entity;
import java.io.Serializable;
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 implements Serializable {
/**
*
*/
private static final long serialVersionUID = 3543286868313801941L;
private int id;
private String name;
private Set<Teacher> teachers = new HashSet<Teacher>();
@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(mappedBy="students")//students 是 teacher类里的student属性
public Set<Teacher> getTeachers() {
return teachers;
}
public void setTeachers(Set<Teacher> teachers) {
this.teachers = teachers;
}
}
package com.hibernate.entity;
import java.io.Serializable;
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;
@Entity
public class Teacher implements Serializable {
/**
*
*/
private static final long serialVersionUID = 3543286868313801941L;
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="s_t",
joinColumns=
@JoinColumn(name="teacherid", referencedColumnName="id"),//当前表里的id
inverseJoinColumns=
@JoinColumn(name="studentid", referencedColumnName="id")//与此相对应的表里的id
)
public Set<Student> getStudents() {
return students;
}
public void setStudents(Set<Student> students) {
this.students = students;
}
}
hibernate.cfg.xml ,ORMappingTest 和之前的一样