Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map the result set of a JPA NativeQuery to a POJO using SqlResultSetMapping

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

@SqlResultSetMapping(name="foo",     classes = {         @ConstructorResult(                 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:

        <dependency>             <groupId>org.hibernate.javax.persistence</groupId>             <artifactId>hibernate-jpa-2.1-api</artifactId>             <version>1.0.0.Final</version>         </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] 
like image 340
mhlandry Avatar asked Aug 07 '14 17:08

mhlandry


People also ask

Can JPA return results as a map?

There is no standard way to get JPA to return a map.

How do you map native query results to entities?

The easiest way to map a query result to an entity is to provide the entity class as a parameter to the createNativeQuery(String sqlString, Class resultClass) method of the EntityManager and use the default mapping. The following snippet shows how this is done with a very simple query.

What is result set mapping?

Annotation Type SqlResultSetMappingSpecifies the mapping of the result of a native SQL query or stored procedure.

How does JPA mapping work?

The Java Persistence API (JPA) is the persistence standard of the Java ecosystem. It allows us to map our domain model directly to the database structure and then gives us the flexibility of manipulating objects in our code - instead of messing with cumbersome JDBC components like Connection , ResultSet , etc.


1 Answers

@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

  • JPA- Joining two tables in non-entity class
like image 77
zbig Avatar answered Sep 22 '22 09:09

zbig