I have a Student entity and want to select only two fields – id
and age
. After reading different posts I wrote the following code:
JavaScript
x
CriteriaQuery<Student> criteriaQuery = ..
var root = criteriaQuery.from(Student.class);
criteriaQuery.multiselect(root.get("id"), root.get("age"));
typedQuery = entityManager.createQuery(criteriaQuery);
List<Student> students = typedQuery.getResultList();
However, it doesn’t work. How to do it using hibernate jpa provider?
Advertisement
Answer
If you only want two fields and use multiselect
you can use a TupleQuery like in the example below:
JavaScript
CriteriaQuery<Tuple> criteriaQuery = criteriaBuilder.createTupleQuery();
var root = criteriaQuery.from(Student.class);
criteriaQuery.multiselect(root.get("id"), root.get("age"));
typedQuery = entityManager.createQuery(criteriaQuery);
List<Tuple> students = typedQuery.getResultList();
To access the values of the tuples use the get
method of it.
E.g.:
JavaScript
Long id = (Long) students.get(0).get(0);