i have quick question related to hibernate and the use of its detachedcriteria.
Three tables all have their ID individually as the parent key.
The tables are table Course , table Teacher and their join table TeacherCourse . Course and Teacher both have one to many relationship to TeacherCourse.
My question now is how do I get all the unique Courses with a Teacher ID
My current code is like
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;
}
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 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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.