使用连接表休眠独立的条件 [英] hibernate detached criteria with join table

查看:56
本文介绍了使用连接表休眠独立的条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与休眠及其分离标准的使用有关的快速问题.

i have quick question related to hibernate and the use of its detachedcriteria.

三个表都各自具有其ID作为父键.

Three tables all have their ID individually as the parent key.

表为表课程,表 Teacher 及其 join表 TeacherCourse . 课程和教师与TeacherCourse都有一对多的关系.

The tables are table Course, table Teacher and their join table TeacherCourse. Course and Teacher both have one to many relationship to TeacherCourse.

我现在的问题是如何获得所有带有教师ID的独特课程

My question now is how do I get all the unique Courses with a Teacher ID

我当前的代码就像

public static ArrayList<Course> getCoursesByTeacher(Teacher teacher){
    ArrayList<Course> courses = new ArrayList<Course>();
    DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Course.class);
    detachedCriteria.add(Restrictions.eq(Key.TEACHER, teacher));
    detachedCriteria.add(Restrictions.eq(Key.OBJSTATUS, Value.ACTIVED));
    List<Object> list = HibernateUtil.detachedCriteriaReturnList(detachedCriteria);
    for(Object o : list){
        courses.add((Course) o);
    }
    return courses;
}

但是两者之间缺少TeacherCourse.我该如何安排教师课程并为教师找到所有独特的课程.

But the TeacherCourse is missing in between. How do I slot in the teacherCourse and find all the unique courses for a teacher.

推荐答案

JB Nizet给出了正确的答案,只是为了使其更清楚,这是我的解决方案:

JB Nizet give the correct answer, just to make it clearer, here is my solution in my situation:

public static ArrayList<Course> getCoursesByTeacher(Teacher teacher){
    ArrayList<Course> courses = new ArrayList<Course>();
    Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();
    List<Object> list = session.createQuery("select c from Course c join c.teacherCourses tc where tc.teacher = :teacher")
            .setParameter("teacher", teacher).list();
    session.getTransaction().commit();
    session.close();
    for(Object o : list){
        courses.add((Course) o);
    }
    return courses;
}

这篇关于使用连接表休眠独立的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆