JPA多对多的增删改查

以学生和老师为例

直接上代码,跟一对多里的操作一样的:

//多对多增加
	@Test
	public void testAdd() {
		Student stu1 = new Student();
		stu1.setName("xuesheng1");
		Student stu2 = new Student();
		stu2.setName("xuesheng2");
		
		Teacher tea1 = new Teacher();
		tea1.setName("laoshi1");
		Teacher tea2 = new Teacher();
		tea2.setName("laoshi2");
		Teacher tea3 = new Teacher();
		tea3.setName("laoshi3");
		
		EntityManager em = MyJPAUtils.getEntityManager();
		EntityTransaction tx = em.getTransaction();
		tx.begin();
		stu1.getTeachers().add(tea1);
		stu1.getTeachers().add(tea2);
		stu2.getTeachers().add(tea2);
		stu2.getTeachers().add(tea3);
		tea1.getStudents().add(stu1);
		tea2.getStudents().add(stu1);
		tea2.getStudents().add(stu2);
		tea3.getStudents().add(stu2);
		
		em.persist(tea1);
		em.persist(tea2);
		em.persist(tea3);
		em.persist(stu1);
		em.persist(stu2);
		tx.commit();
		em.close();
		
	}
	
	//多对多更新
	@Test
	public void testUpdate() {
		Student stu = new Student();
		stu.setName("xuesheng3");
		EntityManager em = MyJPAUtils.getEntityManager();
		EntityTransaction tx = em.getTransaction();
		tx.begin();
		Teacher tea = em.find(Teacher.class, "8945c1566463c6fb016463c6ff780000");
		tea.getStudents().add(stu);
		stu.getTeachers().add(tea);
		em.merge(tea);	//注意先配置好级联更新
		tx.commit();
		em.close();
	}
	
	//多对多删除
	@Test
	public void testDelete() {
		EntityManager em = MyJPAUtils.getEntityManager();
		EntityTransaction tx = em.getTransaction();
		tx.begin();
		Teacher tea = em.find(Teacher.class, "8945c1566463c6fb016463c6ff780000");
		em.remove(tea);
		tx.commit();
		em.close();
		
	}
	
	//多对多查询
	@Test
	public void testQuery() {
		EntityManager em = MyJPAUtils.getEntityManager();
		EntityTransaction tx = em.getTransaction();
		tx.begin();
		Teacher tea = em.find(Teacher.class, "8945c1566463c6fb016463c6ff780000");
		System.out.println(tea);
		Set<Student> students = tea.getStudents();    //对象导航查询,也是懒加载
		System.out.println(students);
		tx.commit();
		em.close();
	}


猜你喜欢

转载自blog.csdn.net/dimples_qian/article/details/80911246