JPA多对多关系映射

在JPA中双向多对多关系,是对等关系,双方都可以作为关系维护端,这里使用Student和Teacher,指定Student为关系维护端

src下在面的META-INF/persistence.xml配置如下:

<?xml version="1.0"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
  <persistence-unit name="itcast" transaction-type="RESOURCE_LOCAL">
      <properties>
         <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
         <property name="hibernate.connection.driver_class" value="org.gjt.mm.mysql.Driver"/>
         <property name="hibernate.connection.username" value="root"/>
         <property name="hibernate.connection.password" value="root"/>
         <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/itcast?useUnicode=true&amp;characterEncoding=UTF-8"/>
         <property name="hibernate.hbm2ddl.auto" value="update"/>
      </properties>
  </persistence-unit>
</persistence>

 关系维护端:Student类

/**
 * 多对多关系,是对等关系,都可以作为维护端
 *1.学生A
 *2.老师B
 *A.getTeachers.add(teacher)
 *中间表(关联表)来存放关系的定义
 *
 *insert into...
 *delete ...
 */

@Entity
@Table(name = "t_student")
public class Student {
	private Integer id;
	private String name;
	private Set<Teacher> teachers=new HashSet<Teacher>();
	@ManyToMany(cascade=CascadeType.REFRESH)
	/**外键定义在关系维护端*/
	/**inverseJoinColumns=@JoinColumn(name="teacher_id"):关系统被维护端外鍵*/
	/**joinColumns=@JoinColumn(name="student_id"):关系维护端外键*/
	@JoinTable(name="t_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 removeTeacher(Teacher teacher){
		if(this.teachers.contains(teacher)){
			teachers.remove(teacher);
		}
	}
	
	
	@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;
		Student other = (Student) obj;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		return true;
	}

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

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	/**构造函数*/
	public Student(String name) {
		super();
		this.name = name;
	}
	/**无参构造*/
	public Student() {
		super();
	}
}

 关系被维护端Teacher类

@Entity
@Table(name = "t_teacher")
public class Teacher {
	private Integer id;
	private String name;
	private Set<Student> students=new HashSet<Student>();
	/**多对多中很少用到级联删除*/
	@ManyToMany(cascade=CascadeType.REFRESH,mappedBy="teachers")
	public Set<Student> getStudents() {
		return students;
	}
	public void setStudents(Set<Student> students) {
		this.students = students;
	}
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	public Integer getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

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

 测试类:

public class ManyToManyTest {

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
	}

	@Test
	public void save() {
		EntityManagerFactory factory = Persistence.createEntityManagerFactory("itcast");
		EntityManager em=factory.createEntityManager();
		em.getTransaction().begin();
		em.persist(new Student("小群"));
		em.persist(new Teacher("李明"));
		em.getTransaction().commit();
		em.close();
		factory.close();
	}
	/**
	 * 建立学生与老师的关系
	 * 1.托管状态
	 * 2.与事务关联起来
	 */
	@Test
	public void saveRelation() {
		EntityManagerFactory factory = Persistence.createEntityManagerFactory("itcast");
		EntityManager em=factory.createEntityManager();
		em.getTransaction().begin();
		Student s=em.find(Student.class, 1);
		s.addTeacher(em.getReference(Teacher.class, 1));
		em.getTransaction().commit();
		em.close();
		factory.close();
	}
	/**
	 * 解除关系
	 */
	@Test
	public void removeRelation() {
		EntityManagerFactory factory = Persistence.createEntityManagerFactory("itcast");
		EntityManager em=factory.createEntityManager();
		em.getTransaction().begin();
		Student s=em.find(Student.class, 1);
		s.removeTeacher(em.getReference(Teacher.class, 1));
		em.getTransaction().commit();
		em.close();
		factory.close();
	}
	/**
	 * 删除老师(关系被维护端不能解除关系,所以不能删除)
	 */
	@Test
	public void deleteTeacher1() {
		EntityManagerFactory factory = Persistence.createEntityManagerFactory("itcast");
		EntityManager em=factory.createEntityManager();
		em.getTransaction().begin();
		em.remove(em.getReference(Teacher.class, 1));
		em.getTransaction().commit();
		em.close();
		factory.close();
	}
	/**
	 * 删除老师(先解除关系,再删除,可以删除)
	 */
	@Test
	public void deleteTeacher2() {
		EntityManagerFactory factory = Persistence.createEntityManagerFactory("itcast");
		EntityManager em=factory.createEntityManager();
		em.getTransaction().begin();
		Student s=em.find(Student.class, 1);
		Teacher t=em.getReference(Teacher.class, 1);
		s.removeTeacher(t);
		em.remove(t);
		em.getTransaction().commit();
		em.close();
		factory.close();
	}
	/**
	 * 关系维护端,可以直接删除,删除 的同时,移除关系
	 */
	@Test
	public void deleteStudnet() {
		EntityManagerFactory factory = Persistence.createEntityManagerFactory("itcast");
		EntityManager em=factory.createEntityManager();
		em.getTransaction().begin();
		em.remove(em.getReference(Student.class, 1));
		em.getTransaction().commit();
		em.close();
		factory.close();
	}
}

 多对多关系映射图
JPA多对多关系映射_第1张图片
 

你可能感兴趣的:(jpa,manytomany,多对多,关系映射)