how do i cast the untyped list from an entitymanager query to a typed list?

Viewed 1121

I am unable to turn the List returned by the getResultList() method into a List<SeedCalendarResultDTO> through mapping with stream. When i collect the result the collect method would supposedly return an Object instead of List<SeedCalendarResultDTO> and i don't understand why this is happening. In the doc i can read that getResultList returns an untyped List and not an object, so why does the collect method return an object then? Heres the relevant code snippet:

Query query = entityManager.createQuery(queryBuilder.toString());
Object collect = query.getResultList().stream()
                                      .map(object -> (SeedCalendarResultDTO) object)
                                      .collect(Collectors.toList());

I can't change Object collect to List collect because it creates a compile error. I don't want to use NamedQuery either because the query string is constructed dynamically.

EDIT: This works just fine for some reason, but undesirable because now it is still a list of objects. List<SeedCalendarResultDTO> results = query.getResultList();

1 Answers

You can use TypedQuery to easily get a typed list.

   TypedQuery<SeedCalendarResultDTO> query = em.createQuery(queryBuilder.toString(), SeedCalendarResultDTO,class);
   List<SeedCalendarResultDTO> results = query.getResultList();

But your code should also work:

Query query = entityManager.createQuery(queryBuilder.toString());
List<SeedCalendarResultDTO> results = query.getResultList();

I would prefer the TypedQuery because you don't need to perform an unchecked conversion.

Related