JPA多对多

系统 1871 0

JPA多对多

维护端注解

@ManyToMany (cascade = CascadeType.REFRESH)

@JoinTable (//关联表

                   name =  "student_teacher" , //关联表名

                   inverseJoinColumns =  @JoinColumn (name =  "teacher_id" ),//被维护端外键

                   joinColumns =  @JoinColumn (name =  "student_id" ))//维护端外键

被维护端注解

@ManyToMany(

                   cascade = CascadeType.REFRESH,

                   mappedBy = "teachers",//通过维护端的属性关联

                   fetch = FetchType.LAZY)

关系维护端删除时,如果中间表存在些纪录的关联信息,则会删除该关联信息;

关系被维护端删除时,如果中间表存在些纪录的关联信息,则会删除失败 .

 

 

以学生和老师的对应关系为例。一个学生可以拥有多个老师,一个老师也可以拥有多个学生。

学生实体类

Student.java代码 复制代码
  1. package com.taoistwar.jpa.entity.manytomany;   
  2.   
  3. import java.util.HashSet;   
  4. import java.util.Set;   
  5.   
  6. import javax.persistence.CascadeType;   
  7. import javax.persistence.Column;   
  8. import javax.persistence.Entity;   
  9. import javax.persistence.GeneratedValue;   
  10. import javax.persistence.GenerationType;   
  11. import javax.persistence.Id;   
  12. import javax.persistence.JoinColumn;   
  13. import javax.persistence.JoinTable;   
  14. import javax.persistence.ManyToMany;   
  15.   
  16. @Entity   
  17. public class Student {   
  18.     private Integer id;   
  19.     private String name;   
  20.     private Set<Teacher> teachers = new HashSet<Teacher>();   
  21.   
  22.     @Id   
  23.     @GeneratedValue(strategy = GenerationType.AUTO)   
  24.     public Integer getId() {   
  25.         return id;   
  26.     }   
  27.   
  28.     public void setId(Integer id) {   
  29.         this.id = id;   
  30.     }   
  31.   
  32.     @Column(nullable = false, length =  16 )   
  33.     public String getName() {   
  34.         return name;   
  35.     }   
  36.   
  37.     public void setName(String name) {   
  38.         this.name = name;   
  39.     }   
  40.   
  41.     @ManyToMany(cascade = CascadeType.REFRESH)   
  42.     @JoinTable(name =  "student_teacher" , inverseJoinColumns = @JoinColumn(name =  "teacher_id" ), joinColumns = @JoinColumn(name =  "student_id" ))   
  43.     public Set<Teacher> getTeachers() {   
  44.         return teachers;   
  45.     }   
  46.   
  47.     public void setTeachers(Set<Teacher> teachers) {   
  48.         this.teachers = teachers;   
  49.     }   
  50.   
  51.     public void addTeacher(Teacher teacher) {   
  52.         this.teachers.add(teacher);   
  53.     }   
  54.   
  55.     public void removeTeachers(Teacher teacher) {   
  56.         this.teachers.remove(teacher);   
  57.     }   
  58.   
  59. }  
      package com.taoistwar.jpa.entity.manytomany;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;

@Entity
public class Student {
	private Integer id;
	private String name;
	private Set<Teacher> teachers = new HashSet<Teacher>();

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	@Column(nullable = false, length = 16)
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@ManyToMany(cascade = CascadeType.REFRESH)
	@JoinTable(name = "student_teacher", inverseJoinColumns = @JoinColumn(name = "teacher_id"), joinColumns = @JoinColumn(name = "student_id"))
	public Set<Teacher> getTeachers() {
		return teachers;
	}

	public void setTeachers(Set<Teacher> teachers) {
		this.teachers = teachers;
	}

	public void addTeacher(Teacher teacher) {
		this.teachers.add(teacher);
	}

	public void removeTeachers(Teacher teacher) {
		this.teachers.remove(teacher);
	}

}

    

 重点在于:

Java代码 复制代码
  1. @ManyToMany (cascade = CascadeType.REFRESH)   
  2.      @JoinTable (name =  "student_teacher" , inverseJoinColumns =  @JoinColumn (name =  "teacher_id" ), joinColumns =  @JoinColumn (name =  "student_id" ))   
  3.      public  Set<Teacher> getTeachers() {   
  4.          return  teachers;   
  5.     }  
      @ManyToMany(cascade = CascadeType.REFRESH)
	@JoinTable(name = "student_teacher", inverseJoinColumns = @JoinColumn(name = "teacher_id"), joinColumns = @JoinColumn(name = "student_id"))
	public Set<Teacher> getTeachers() {
		return teachers;
	}


    

 老师实体类

Teacher.java代码 复制代码
  1. package com.taoistwar.jpa.entity.manytomany;   
  2.   
  3. import java.util.HashSet;   
  4. import java.util.Set;   
  5.   
  6. import javax.persistence.CascadeType;   
  7. import javax.persistence.Column;   
  8. import javax.persistence.Entity;   
  9. import javax.persistence.FetchType;   
  10. import javax.persistence.GeneratedValue;   
  11. import javax.persistence.GenerationType;   
  12. import javax.persistence.Id;   
  13. import javax.persistence.ManyToMany;   
  14.   
  15. @Entity   
  16. public class Teacher {   
  17.     private Integer id;   
  18.     private String name;   
  19.     private Set<Student> students = new HashSet<Student>();   
  20.   
  21.     @Id   
  22.     @GeneratedValue(strategy = GenerationType.AUTO)   
  23.     public Integer getId() {   
  24.         return id;   
  25.     }   
  26.   
  27.     public void setId(Integer id) {   
  28.         this.id = id;   
  29.     }   
  30.   
  31.     @Column(nullable = false, length =  16 )   
  32.     public String getName() {   
  33.         return name;   
  34.     }   
  35.   
  36.     public void setName(String name) {   
  37.         this.name = name;   
  38.     }   
  39.   
  40.     @ManyToMany(cascade = CascadeType.REFRESH, mappedBy =  "teachers" , fetch = FetchType.LAZY)   
  41.     public Set<Student> getStudents() {   
  42.         return students;   
  43.     }   
  44.   
  45.     public void setStudents(Set<Student> students) {   
  46.         this.students = students;   
  47.     }   
  48.   
  49.       @Override   
  50.     public int hashCode() {   
  51.         final int prime =  31 ;   
  52.         int result =  1 ;   
  53.         result = prime * result + ((id == null) ?  0  : id.hashCode());   
  54.         return result;   
  55.     }   
  56.   
  57.     @Override   
  58.     public boolean equals(Object obj) {   
  59.         if (this == obj)   
  60.             return true;   
  61.         if (obj == null)   
  62.             return false;   
  63.         if (getClass() != obj.getClass())   
  64.             return false;   
  65.         Teacher other = (Teacher) obj;   
  66.         if (id == null) {   
  67.             if (other.id != null)   
  68.                 return false;   
  69.         } else if (!id.equals(other.id))   
  70.             return false;   
  71.         return true;   
  72.     }   
  73. }  
      package com.taoistwar.jpa.entity.manytomany;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;

@Entity
public class Teacher {
	private Integer id;
	private String name;
	private Set<Student> students = new HashSet<Student>();

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	@Column(nullable = false, length = 16)
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@ManyToMany(cascade = CascadeType.REFRESH, mappedBy = "teachers", fetch = FetchType.LAZY)
	public Set<Student> getStudents() {
		return students;
	}

	public void setStudents(Set<Student> students) {
		this.students = students;
	}

      @Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Teacher other = (Teacher) obj;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		return true;
	}
}

    

 重点在于:

Java代码 复制代码
  1. @ManyToMany (cascade = CascadeType.REFRESH, mappedBy =  "teachers" , fetch = FetchType.LAZY)   
  2.      public  Set<Student> getStudents() {   
  3.          return  students;   
  4.     }  
      @ManyToMany(cascade = CascadeType.REFRESH, mappedBy = "teachers", fetch = FetchType.LAZY)
	public Set<Student> getStudents() {
		return students;
	}
    

 拥有mappedBy注解的实体类为关系被维护端,另外的实体类为关系维护端的。顾名思意,关系的维护端对关系(在多对多为中间关联表)的CRUD做操作。关系的被维护端没有该操作,不能维护关系。

测试类

Java代码 复制代码
  1. package  com.taoistwar.jpa.entity.manytomany;   
  2.   
  3. import  javax.persistence.EntityManager;   
  4. import  javax.persistence.EntityManagerFactory;   
  5. import  javax.persistence.Persistence;   
  6.   
  7. import  org.junit.Test;   
  8.   
  9. public   class  ManyToMany {   
  10.      @Test   
  11.      public   void  save() {   
  12.         EntityManagerFactory emf = Persistence   
  13.                 .createEntityManagerFactory( "JPAPU" );   
  14.         EntityManager em = emf.createEntityManager();   
  15.         em.getTransaction().begin();   
  16.         Student student =  new  Student();   
  17.         student.setName( "小李" );   
  18.         Teacher teacher =  new  Teacher();   
  19.         teacher.setName( "大李" );   
  20.         em.persist(student);   
  21.         em.persist(teacher);   
  22.         em.getTransaction().commit();   
  23.         emf.close();   
  24.     }   
  25.        
  26.      @Test   
  27.      public   void  bind() {   
  28.         EntityManagerFactory emf = Persistence   
  29.                 .createEntityManagerFactory( "JPAPU" );   
  30.         EntityManager em = emf.createEntityManager();   
  31.         em.getTransaction().begin();   
  32.         Student student = em.find(Student. class 1 );   
  33.         Teacher teacher = em.find(Teacher. class 1 );   
  34.         student.addTeacher(teacher);   
  35.         em.persist(student);   
  36.         em.getTransaction().commit();   
  37.         emf.close();   
  38.     }   
  39.        
  40.      @Test   
  41.      public   void  unbind() {   
  42.         EntityManagerFactory emf = Persistence   
  43.                 .createEntityManagerFactory( "JPAPU" );   
  44.         EntityManager em = emf.createEntityManager();   
  45.         em.getTransaction().begin();   
  46.         Student student = em.find(Student. class 1 );   
  47.         Teacher teacher = em.find(Teacher. class 1 );   
  48.         student.removeTeachers(teacher);   
  49.         em.persist(student);   
  50.         em.getTransaction().commit();   
  51.         emf.close();   
  52.     }   
  53.        
  54.      @Test   
  55.      public   void  removeTeacher() {   
  56.         EntityManagerFactory emf = Persistence   
  57.                 .createEntityManagerFactory( "JPAPU" );   
  58.         EntityManager em = emf.createEntityManager();   
  59.         em.getTransaction().begin();   
  60.          // 关系被维护端删除时,如果中间表存在些纪录的关联信息,则会删除失败   
  61.         em.remove(em.getReference(Teacher. class 1 ));   
  62.         em.getTransaction().commit();   
  63.         emf.close();   
  64.     }   
  65.        
  66.      @Test   
  67.      public   void  removeStudent() {   
  68.         EntityManagerFactory emf = Persistence   
  69.                 .createEntityManagerFactory( "JPAPU" );   
  70.         EntityManager em = emf.createEntityManager();   
  71.         em.getTransaction().begin();   
  72.          // 关系维护端删除时,如果中间表存在些纪录的关联信息,则会删除该关联信息   
  73.         em.remove(em.getReference(Student. class 1 ));   
  74.         em.getTransaction().commit();   
  75.         emf.close();   
  76.     }   
  77.        
  78. }  

http://taoistwar.iteye.com

JPA多对多


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论