'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 1:[1]
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>
Solution 2:[2]
Before fixing your code you must be clear about the reasons for java.lang.IllegalArgumentException. Refer
Reasons for java.lang.IllegalArgumentException
- When Arguments out of range. For example, the percentage should lie between 1 to 100. If the user entered 101 then an IllegalArugmentExcpetion will be thrown.
- When argument format is invalid. For example, if our method requires date format like YYYY/MM/DD but if the user is passing YYYY-MM-DD. Then our method can’t understand then IllegalArugmentExcpetion will be thrown.
- When a method needs non-empty string as a parameter but the null string is passed.
Once you are clear about the issues, please refer to the solution which was already provided by @Panagiotis Bougioukas
Issue - Argument format is invalid
Most probably below solution should work(Not tested)
@Repository
public class EventRepositoryImpl {
@PersistenceContext
private EntityManager entityManager;
public List<EventDTO> getLatestEventsFiltered(String sql, int limit) {
var query = entityManager.createQuery(sql, Event.class);
query.setMaxResults(limit);
var resultList = query.getResultList().
stream().map(this::convertToDto).
collect(Collectors.toList());
return resultList;
}
private EventDTO convertToDto(Event event) {
var dto = new EventDTO();
// convert event to eventdto here
return dto;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Panagiotis Bougioukos |
| Solution 2 |
