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

Time:03-28

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?

CodePudding user response:

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>

CodePudding user response:

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;
    }
}
  • Related