Search code examples
javasqlspringjpaentitymanager

IllegalArgumentException: Mismatch in requested result type - but Type is set


I get following error:

IllegalArgumentException: Mismatch in requested result type [com.taqwaapps.entity.Event] and actual result type [com.taqwaapps.dto.EventDTO]

But my code points to the type I intent to receive:

@Repository
public class EventRepositoryImpl  {

    @PersistenceContext
    private EntityManager entityManager;

    public List<EventDTO> getLatestEventsFiltered(String sql, int limit) {
        Query query = entityManager.createQuery(sql, Event.class);
        query.setMaxResults(limit);

        List<EventDTO> resultList = (List<EventDTO>) query.getResultList();
        return resultList;
    }
}

Info: The objects Event and EventDTO are different.

Any Idea?


Solution

  • Query query = entityManager.createQuery(sql, Event.class); <---- Here you inform the library that it must parse the result using Event.class

    But here List<EventDTO> resultList = (List<EventDTO>) query.getResultList(); you try to parse the result using EventDTO.class

    Change it into List<Event> resultList = query.getResultList();

    and then use some converter to convert the List<Event> into a List<EventDTO>