JPA CriteriaQuery multiselect from several entities

12.1k views Asked by At

Right now, I am using the method multiselect of CriteriaQuery to put some values from entity Termine in entity Task like this:

CriteriaBuilder builder = getEm().getCriteriaBuilder();
        CriteriaQuery<Task> taskCriteria = builder.createQuery(Task.class);
        Root<Termin> terminRoot = taskCriteria.from(Termin.class);
        taskCriteria.multiselect(terminRoot.get("text"), terminRoot.get("empfaenger"), terminRoot.get("datVon"));
        taskCriteria.where(builder.equal(terminRoot.get("empfaenger"), "000"));
        List<Task> task = getEm().createQuery(taskCriteria).getResultList();
        return task;

This is working fine, but now I am willing to gather the values text, empfaenger and datVon not only from the entity Termine but also from the entity Aufgabe, so that I will have a list of Tasks, that contains every Termin and Aufgabe which are having the same empfaenger.

Is it possible? If yes, how?

Thanks a lot in advance for your help!

2

There are 2 answers

1
jklee On BEST ANSWER

I would derive both classes from task.

@Entity(name="Task")
@Inheritance(strategy = InheritanceType.JOINED)
@NamedQuery(name="Task.findAll", query="SELECT t FROM Task t") 
public class Task {

    @Id
    Long id;

    String text;

    String empfaenger;
}

@Entity
public class Termin extends Task{
    ...
}

@Entity
public class Aufgabe extends Task{
    ...
}

And select them with a named query

List<Task> resultList = entityManager.createNamedQuery("Task.findAll",Task.class).getResultList();

or a criteria query with Task as Root.

1
ucas On

This is the way I did to collect data from multiple entities (custom Select). For example, multiple entities:

Root<InflowEntity> rootInflow = criteriaQuery.from(InflowEntity.class);
Root<OutflowEntity> rootOutflow = criteriaQuery.from(OutflowEntity.class);

You select the attributes you need from the above 2:

criteriaQuery.multiselect(rootInflow.get("inflowID"), rootInflow.get("name"),
rootOutflow.get("count"), rootOutflow.get("dateRange"));

Add the predicates (constraints) you need, for example:

Predicate[] predicates = new Predicate[2];
predicates[0] = criteriaBuilder.equal(rootInflow.get("uuid"), loginContext.getUuid());
predicates[1] = criteriaBuilder.equal(rootOutflow.get("uuid"), loginContext.getUuid()); 

Process the results:

criteriaQuery.where(predicates);                        
List<ResultsBean> results = session.createQuery(criteriaQuery).getResultList();

This Java bean (this is not the Hibernate entity), ResultsBean, stores the results. That is, it needs to have a constructor to accommodate the input the way the multiselect is arranged.