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]
I able to do it this way:
I have a slightly varied answer which is just derived from wildloop's answer.
Here is my answer:
Constants class: Constants.java
Result Mapping Class: TestQueryResult.java
Then... somewhere in my Repository Implementation code:
... then violah! I got some results :D!
Cheers,
Artanis Zeratul
This is not really an entity as it does not match any database table. But the
@Entity
and the@Id
annotations are compulsories for JPA to understand the mapping. If you don't really want to have@Entity / @Id
in that class, you can remove the@SqlResultSetMapping
annotation and put it in any other entity as far as JPA can scan it.You should also make sure that your
@ComponentScan
content the corresponding package, if you are using a java based spring configuration, you should explicitly declare your entity in thepersistence.xml/orm.xml
under theMETA-INF
directory.This is the call
I'm using Spring, JPA 2.1, Hibernate 5 and Oracle, i think this might not be possible with JPA lower version, find more http://www.thoughts-on-java.org/result-set-mapping-complex-mappings/
QLRM could be a alternative: http://simasch.github.io/qlrm/
It is not related to a specific JPA implementation and also works with JDBC.
@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 exampleShort working example:
DTO POJO class
Repository bean: