package com.bjsxt.hibernate;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Embedded;
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.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
@Entity
@Table(name="t_teacher")
public class User {
@Id
@GeneratedValue
private int id;
private String name;
@ManyToMany
@JoinTable(name="t_teacher_student",joinColumns={@JoinColumn(name="teacher_Id")},inverseJoinColumns={@JoinColumn(name="student_Id")})
private Set<Group> students = new HashSet<Group>();
public Set<Group> getStudents() {
return students;
}
public void setStudents(Set<Group> students) {
this.students = students;
}
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;
}
}
·······························································
package com.bjsxt.hibernate;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
@Entity
@Table(name="t_student")
public class Group {
@Id
@GeneratedValue
private int id;
private String name;
@ManyToMany(mappedBy="students") //与单向的多对多就 只多了 这一个地方
private Set<User> teachers = new HashSet<User>();
public Set<User> getTeachers() {
return teachers;
}
public void setTeachers(Set<User> teachers) {
this.teachers = teachers;
}
public int getId() {
return id;
}
// public Set<User> getUsers() {
// return users;
// }
// public void setUsers(Set<User> users) {
// this.users = users;
// }
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
原文:http://www.cnblogs.com/lize1215/p/7643032.html