mhlandry mhlandry - 8 months ago 124
Java Question

Mapping NativeQuery results into a POJO

I am attempting to map the results of a Native query to a POJO using @SqlResultSetMapping with @ConstructorResult. Here is my code:

classes = {
targetClass = Bar.class,
columns = {
@ColumnResult(name = "barId", type = Long.class),
@ColumnResult(name = "barName", type = String.class),
@ColumnResult(name = "barTotal", type = Long.class)

public class Bar {

private Long barId;
private String barName;
private Long barTotal;


And then in my DAO:

Query query = em.createNativeQueryBar.QUERY, "foo");
... set some parameters ...
List<Bar> list = (List<Bar>) query.getResultList();

I have read that this functionality is only supported in JPA 2.1, but that is what I am using. Here's my dependency:


I found a couple of resources, including this one: @ConstructorResult mapping in jpa 2.1. But I am still not having any luck.

What am I missing? Why can't the SqlResultSetMapping be found?

javax.persistence.PersistenceException: org.hibernate.MappingException: Unknown SqlResultSetMapping [foo]

Answer Source

@SqlResultSetMapping annotation should not be put on a POJO. Put it at (any) @Entity class. "Unknown SqlResultSetMapping [foo]" tells you, that JPA provider doesn't see any mapping under name 'foo'. Please see another answer of mine for the correct example