Thursday, 8 April 2021

Getting a Native Query Typed in JPA

Recently I tried using a native query to return a result.

This worked fine, except that I had to cast the resulting list to the appropriate list. (which is ugly).

Like so:

List<Room> rooms = (List<Room>) getEntityManager().createNativeQuery(AdminRoom.GET_SEARCH_QUERY)
        .setParameter(1, "%" + description + "%")
        .setMaxResults(pageSize)
        .setFirstResult(offset)
        .getResultList();

I thought I could use the same thing I use daily in my createNamedQuery calls, namely add the appropriate class behind it.

Like so:

List<Room> rooms = (List<Room>) getEntityManager().createNativeQuery(AdminRoom.GET_SEARCH_QUERY, Room.class)...

Unfortunately, the return value of the createNativeQuery method is "Query" which is totally untyped, contrary to "TypedQuery", which I would have liked.

Of course, people have already found this out when I looked it up1.

The API seems to be a little wonky in that area.

References

[1] StackOverflow - entityManager.createNativeQuery does not return a typed result
https://stackoverflow.com/questions/54109546/entitymanager-createnativequery-does-not-return-a-typed-result

No comments:

Post a Comment