3

I have a problem getting the following scenario to work. A student can take tests. A student have over time taken a few tests and got a score for each test. Each student entity have a list of tests that they have completed mapped as @OneToMany.

Now I want to select all students that have completed tests on a range of grouped criterions. I want for example to search for all students that have:

Group 1: Completed "Test 1" and got a score "between 75 and 100"

and/or

Group 2: Completed "Test 2" and got a score "between 50 and 80"

This is what I have so far but it does not do what I need (cannot search by multiple parameters meaning that I have to perform the query multiple times):

SELECT s FROM Student s JOIN s.tests t WHERE t.score BETWEEN :minScore AND :maxScore AND t.testName = :testName

Is there a way to use a single NamedQuery to achieve what I want? To retrieve all Students that have completed a test that matches at least one of the parameter groups above? I've been experimenting with joins but keep running into the wall.

I made a sample code skeleton below to illustrate what I'm trying to do.

@Entity
@NamedQueries({
    @NamedQuery(name="Student.findStudentByParams", query="????????") // What should this query look like to satisfy the criteria? (see below for more detail)
})
public class Student {
    // .. Some other variables that are not relevant for this example

    @Id
    private String name;

    @OneToMany(fetch=FetchType.EAGER, mappedBy = "student")
    private List<Test> tests;

    // Setters and getters
}

@Entity
public class Test {
    private double score;
    private String testName;
    // .. Some other variables that are not relevant for this example

    @ManyToOne(cascade=CascadeType.ALL)
    private Student student;

    // Setters and getters
}

public class SearchParameters {
    private double minScore;
    private double maxScore;
    private String testName; 

    public SearchParameters(String minScore, String maxScore, String testName) {
        this.minScore = minScore;
        this.maxScore = maxScore;
        this.testName = testName;
    }

    // Setters and getters
}

public class MainClass {
    public static List<Student> getStudents(List<SearchParameters> searchParams) {

        // Database initialization stuff

        // What should the query look like to find all students that match any of the combined requirements in the searchParams list? 
        // Is it possible to do in a single query or should i make multiple ones?
        // What parameters should i set? Is it possible to put in the entire array and do some sort of join?

        // Retrieve all students which matches any of these search parameters:
        // Have either:
        //      Completed "Test 1" and got a score between 75 and 100
        // and/or:
        //      Completed "Test 2" and got a score between 50 and 80
        Query namedQuery = em.createNamedQuery("Student.findStudentByParams");
        namedQuery.setParameter(??); 

        return (List<Student>)namedQuery.getResultList();

    }
    public static void main() {
        List<SearchParams> searchParams = new ArrayList<SearchParams();
        searchParams.add(new SearchParameters(75,100, "Test 1"));
        searchParams.add(new SearchParameters(50,80, "Test 2"));

        // Retrieve all students which matches any of these search parameters:
        // Have either:
        //      Completed "Test 1" and got a score between 75 and 100
        // and/or:
        //      Completed "Test 2" and got a score between 50 and 80
        ArrayList<Student> students = getStudents(searchParams);
        for(Student s: students) // Print all user that match the criteria
        {
            System.out.println("Name: " + s.getName());
        }
    }   
}
MrKiane
  • 4,803
  • 2
  • 17
  • 27
  • Have a look at Criteria Query builder. You can build an array of predicates: http://www.ibm.com/developerworks/java/library/j-typesafejpa/ – perissf Jan 16 '12 at 17:03

2 Answers2

3

You need to use Criteria Builder (and eventually the canonical Metamodel).

Try something like this (code not tested):

EntityManager em;    // put here your EntityManager instance
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Student> cq = cb.createQuery(Student.class);
Root<Student> student = cq.from(Student.class);
Predicate predicate = cb.disjunction();
for (SearchParams param : searchParams) {
    ListJoin<Student, Test> tests = student.join(Student_.tests);
    Predicate tempPredicate1 = cb.equal(tests.get(Test_.testName), param.getTestName());
    Predicate tempPredicate2 = cb.ge(tests.get(Test_.score), param.getMinScore());
    Predicate tempPredicate3 = cb.le(tests.get(Test_.score), param.getMaxScore());
    Predicate tempPredicate = cb.and(tempPredicate1, tempPredicate2, tempPredicate3);
    predicate = cb.or(predicate, tempPredicate);
}
cq.where(predicate);
TypedQuery<Student> tq = em.createQuery(cq);
return tq.getResultList();
perissf
  • 15,979
  • 14
  • 80
  • 117
1

I don't see how it would be possible without composing the query dynamically. Consider using the Criteria API to create it.

I would design the query like this:

select s from Student s where
    exists (select t.id from Test t where t.student.id = s.id and ...)
or
    exists (select t.id from Test t where t.student.id = s.id and ...)
or
    exists (...)

As you see, there's a repeating pattern, and all these subqueries are similar an are combined into a disjunction.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255