Skip to content
Advertisement

How to select only some fields using JPA criteria

I have a Student entity and want to select only two fields – id and age. After reading different posts I wrote the following code:

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:

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.:

Long id = (Long) students.get(0).get(0);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement