hibernate级联之多对多转换为多对一的问题剖析

[html] view plaincopyprint? 这里与多对多不同的是借用了一个中间类StudentCourse来达到把多对多的问题转换为多对一的问题,下面来举例具体介绍: 先看看三个最重要的xxx.hbm.xml文件内部信息 Student.hbm.xml <?xml version="1.0"?> Course.hbm.xml <?xml version="1.0"?> StudentCourse.hbm.xml <?xml version="1.0"?> 再看看测试文件TestApp.java package com.hbsi.many2manyTOone2many; import java.util.Set; import org.hibernate.Session; import org.junit.Test; import com.hbsi.utils.HibernateSessionFactory; public class TestApp { Session session = HibernateSessionFactory.getSession(); @Test public void add(){ session.beginTransaction(); Student stu = new Student(); stu.setName("keven"); Course c1 = new Course(); c1.setName("java"); Course c2 = new Course(); c2.setName("mysql"); StudentCourse sc1 = new StudentCourse(); sc1.setS(stu); sc1.setC(c1); sc1.setScore(99); session.save(sc1); StudentCourse sc2 = new StudentCourse(); sc2.setS(stu); sc2.setC(c2); sc2.setScore(89); session.save(sc2); session.getTransaction().commit(); HibernateSessionFactory.closeSession(); } @Test public void find(){ Student stu = (Student) session.get(Student.class,1); Set scs = stu.getSc(); for(StudentCourse sc : scs){ System.out.println(sc.getS().getName()+":"+sc.getC().getName()+"---"+sc.getScore()); } } } 这里与多对多不同的是借用了一个中间类StudentCourse来达到把多对多的问题转换为多对一的问题,下面来举例具体介绍: 先看看三个最重要的xxx.hbm.xml文件内部信息Student.hbm.xml<?xml version="1.0"?> Course.hbm.xml<?xml version="1.0"?> StudentCourse.hbm.xml<?xml version="1.0"?> 再看看测试文件TestApp.javapackage com.hbsi.many2manyTOone2many; import java.util.Set; import org.hibernate.Session;import org.junit.Test; import com.hbsi.utils.HibernateSessionFactory; public class TestApp { Session session = HibernateSessionFactory.getSession(); @Test public void add(){ session.beginTransaction(); Student stu = new Student(); stu.setName("keven"); Course c1 = new Course(); c1.setName("java"); Course c2 = new Course(); c2.setName("mysql"); StudentCourse sc1 = new StudentCourse(); sc1.setS(stu); sc1.setC(c1); sc1.setScore(99); session.save(sc1); StudentCourse sc2 = new StudentCourse(); sc2.setS(stu); sc2.setC(c2); sc2.setScore(89); session.save(sc2); session.getTransaction().commit(); HibernateSessionFactory.closeSession(); } @Test public void find(){ Student stu = (Student) session.get(Student.class,1); Set scs = stu.getSc(); for(StudentCourse sc : scs){ System.out.println(sc.getS().getName()+":"+sc.getC().getName()+"---"+sc.getScore()); } }}

你可能感兴趣的:(hibernate级联之多对多转换为多对一的问题剖析)