hibernate manytomany 双向

Posted 跳刀玛利亚

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了hibernate manytomany 双向相关的知识,希望对你有一定的参考价值。

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;
}


}


























































































以上是关于hibernate manytomany 双向的主要内容,如果未能解决你的问题,请参考以下文章

Hibernate学习笔记 --- 创建基于中间关联表的多对多映射关系

Hibernate - 自动 @ManyToMany 更新

Jpa中ManyToMany和OneToMany的双向控制

Jpa中ManyToMany和OneToMany的双向控制

添加到双向 ManyToMany 集合检索已经相关的所有条目

Hibernate @ManyToMany 单向关系[重复]