Leo
Leo

Reputation: 6570

How to project a JPA Tuple result into an entity

I have a query like this

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();

It returns Tuples of 2 ids, jeid and jid.

These two ids identify uniquely another entity (let's say it's the composite PK of entity A), so instead of returning a list of Tuples, I'd like to return a list of A's.

Is there any way to do that in this same Criteria query? (of course, I know how to get these IDs and just issue another query, but I feel there must be the right way to project these IDs into another entity)

Upvotes: 3

Views: 2730

Answers (1)

Koitoer
Koitoer

Reputation: 19533

Ok, before try to add the predicate just try this.

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);

If that works, it should you will be able to return Job objects and then you can fetch records from there, consider using job.fetch("jobExecution");

Then Add the predicate cq.where according to this new structure of retrieval

Upvotes: 2

Related Questions