我有这样的查询
public List<Tuple> listReocurringUndroppedJobs() {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Tuple> cq= cb.createTupleQuery();
Root<JobEvent> event = cq.from(JobEvent.class);
Path<JobExecution> je = event.get(JobEvent_.jobExecution);
Path<Job> j = event.get(JobEvent_.job);
Predicate predicate = cb.conjunction();
Predicate p1 = cb.equal(event.get(JobEvent_.event), "ENQUEUED");
Predicate p2 = cb.gt(cb.count(event), 1);
predicate = cb.and(p1,p2);
cq.multiselect(je.get(JobExecution_.id),j.get(Job_.id));
cq.groupBy(event.get(JobEvent_.event),j.get(Job_.id),je.get(JobExecution_.id)).having(predicate);
TypedQuery<Tuple> tq = entityManager.createQuery(cq);
//for (Tuple t : tq.getResultList()) {
// Long jeid = (Long)t.get(0);
// Long jid = (Long)t.get(1);
//}
return tq.getResultList();
它返回2个ID,jeid和jid的元组。
这两个id唯一地标识另一个实体(假设它是实体A的复合PK),所以我不想返回一个元组列表,而是返回一个A列表。
在同一个Criteria查询中有没有办法做到这一点? (当然,我知道如何获取这些ID并发出另一个查询,但我觉得必须有正确的方法将这些ID投射到另一个实体中)
答案 0 :(得分:1)
好的,在尝试添加谓词之前,试试这个。
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Job> cq= cb.createQuery(Job.class);
Root<Job> job = cq.from(Job.class);
Join<Job,JobExecutions> jobExec = job.join("jobExecution"); <--Assuming this is the name of property
Join<JobExecutions,JobEvents > jobEve = jobExec .join("event"); <--Assuming this is the name of property
cq.select(job);
TypedQuery<Job> tq = entityManager.createQuery(cq);
如果有效,你应该能够返回Job对象,然后你可以从那里获取记录,考虑使用job.fetch(“jobExecution”);
然后根据这个新的检索结构
添加谓词cq.where