AlexSC
AlexSC

Reputation: 1923

Hibernate Complex query through many Entities

I have a Java-SE 1.6/JPA application that uses Hibernate 3.6 to perform persistence. Such an application has a domain model like shown below (in a simplified form):

@Entity
@Table(name = "students")
public class Student implements Serializable {

    // many fields, getters and setters

    @OneToMany(mappedBy="student", cascade=CascadeType.ALL)
    private List<Enrollment> enrollments = new ArrayList<Enrollment>();
    public Collection<Enrollment> getEnrollments() {
        return Collections.unmodifiableCollection(enrollments);
    }
}

@Entity
@Table(name = "enrollments")
public class Enrollment implements Serializable {

    // many fields, getters and setters

    @ManyToOne
    private Student student;
    public Student getStudent() {
        return student;
    }

    @OneToOne
    private Course course;
    public Course getCourse() {
        return course;
    }
}

@Entity
@Table(name = "courses")
public class Course implements Serializable {

    // many fields, getters and setters

}

So, in plain english, this model enable us to model the following domain rule:

"A given student can have a number of enrollments in a number of courses at the same time."

Everything is working splendidly until now. The question here is:

"How to select all the students who have enrollments in a given course?"

So, I have a instance of Course and my job is to select all the instances of Student that are (indirectly) related to that Course (through instances of Enrollment) by using a Hibernate query.

Could someone give me some advices and/or ideas?

Thanks in advance.

Upvotes: 0

Views: 507

Answers (1)

Predrag Maric
Predrag Maric

Reputation: 24403

Try this

select s from Student s join s.enrollments e join e.course c where c.id = :courseId

Using criteria

List<Student> students = session.createCriteria(Student.class).createAlias("enrollments", "e").createAlias("e.course", "c").add(Restrictions.eq("c.id", courseId)).list();

Upvotes: 1

Related Questions