我在使以下方案工作时遇到问题。学生可以参加考试。一名学生随着时间的推移进行了一些测试并获得了每项测试的分数。每个学生实体都有一个他们已完成映射为@OneToMany的测试列表。
现在我想选择所有已完成一系列分组标准测试的学生。例如,我想搜索所有拥有以下内容的学生:
第1组:完成“测试1”并得分“介于75和100之间”
和/或
第2组:完成“测试2”,得分“在50到80之间”
这是我到目前为止所做的,但它不能满足我的需要(不能通过多个参数进行搜索,这意味着我必须多次执行查询):
SELECT s FROM Student s JOIN s.tests t WHERE t.score BETWEEN :minScore AND :maxScore AND t.testName = :testName
有没有办法使用单个NamedQuery来实现我想要的?要检索所有已完成与上述至少一个参数组匹配的测试的学生?我一直在尝试连接,但一直跑到墙上。
我在下面制作了一个示例代码框架,以说明我正在尝试做什么。
@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());
}
}
}
答案 0 :(得分:3)
您需要使用Criteria Builder(最终使用规范的Metamodel)。
尝试这样的事情(未经过测试的代码):
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();
答案 1 :(得分:1)
如果不动态编写查询,我看不出怎么可能。请考虑使用Criteria API创建它。
我会像这样设计查询:
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 (...)
如你所见,有一个重复的模式,所有这些子查询都是相似的,并且被组合成一个分离。