The goal is to get the firstName, lastName, and the list of todos for an employee by using multiselect:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Tuple> q = cb.createTupleQuery();
Root emp = q.from(Employee.class);
q.multiselect(
emp.get("firstName").alias("fname"),
emp.get("lastName").alias("lname"),
emp.get("toDoList").alias("toDoList")
).where(cb.equal(emp.get("id"), 12345));
List<Tuple> tuples = em.createQuery(q).getResultList();
Iterator<Tuple> iter = tuples.iterator();
while(iter.hasNext()){
Tuple t = iter.next();
//t.get("fName"); // returns String
//t.get("lName"); // returns String
//t.get("toDoList"); // returns String
//?????
//...
}
The toDoList is just a simple list of Strings. Let's assume employee 12345 has 4 todos. This means I get the following result set:
---------------------------------
| firstName | lastName | toDo |
---------------------------------
| John | Doe | sleep |
---------------------------------
| John | Doe | eat |
---------------------------------
| John | Doe | play |
---------------------------------
| John | Doe | laugh |
---------------------------------
Now I'm looking for a smart way of creating an instance of ONE Employee and setting its firstName, lastName, and toDoList ONCE:
Employee employee = new Employee();
employee.setFirstName(...);
employee.setLastName(...);
employee.setToDoList(...);
What would be the best approach? Thing would get even more complicated if I would add additional relationships (i.e. favoriteSongs).