高分求Hibernate 多对多查询思路或语句..
如题.
我有3个表:m2m_student(简称stu),m2m_lesson(简称les),m2m_middle(简称mid).
stu 和 les 是多对多的关系.mid 是中间表.
如何查询stu表中的一条学生信息和他所选择的课程名称(les.name)?
一对多的我会查.但是换成多对多就不知道怎么查了?是通过中间表查?还是关联查?
请高手指点思路及语句..谢谢!
------解决方案--------------------
给你一个代码,是我过去写的,表分别是Student,Course,Student_Course,表,对象,关系映射等自己建,DAO如下,相信你会懂的,
public class TestDao {
private static SessionFactory sessionfactory=null;
static
{
sessionfactory=new Configuration().configure().buildSessionFactory();
}
public void saveMessage()
{
Session session=sessionfactory.openSession();
Transaction trs=session.beginTransaction();
try {
StudentPO studenta=new StudentPO("众志");
StudentPO studentb=new StudentPO("小高");
CoursePO course=new CoursePO();
course.setCourseNameA("语文");
course.setCourseNameB("数学");
//构造组件对象
Student_CoursePO student_coursea=new Student_CoursePO(studenta,course,89,98);
Student_CoursePO student_courseb=new Student_CoursePO(studentb,course,78,87);
//建立中间表和科目表的关系
course.getStudent_course().add(student_coursea);
course.getStudent_course().add(student_courseb);
//保存
session.save(studenta);
session.save(studentb);
session.save(course);
trs.commit();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
if(trs!=null)
{
trs.rollback();
}
}finally
{
if(session.isOpen())
{
session.close();
}
}
}
public void readMessage(int studentid)
{
Session session=sessionfactory.openSession();
Transaction trs=session.beginTransaction();
try {
StudentPO student=(StudentPO)session.get(StudentPO.class,Integer.valueOf(studentid));
Hibernate.initialize(student.getStudent_course());
trs.commit();
printMessage(student);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
if(trs!=null)
{
trs.rollback();
}
}finally
{
if(session.isOpen())
{
session.close();
}
}
}
public void printMessage(StudentPO student)
{
if(student!=null)
{
System.out.println("学生姓名:"+student.getStuName());
System.out.println("该学生总成绩:"+student.getSumSourse());
System.out.println("==========================");
Iterator iter=student.getStudent_course().iterator();
while(iter.hasNext())
{
Student_CoursePO student_course=(Student_CoursePO)iter.next();
System.out.println(student_course.getCourse().getCourseNameA()+"成绩:"+student_course.getGradea());
System.out.println(student_course.getCourse().getCourseNameB()+"成绩:"+student_course.getGradeb());
}
}
}
}