Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA native query return class

Tags:

java

jpa

In the JPA, I defined a native sql which will return String,

@NamedNativeQuery(name = "alert", 
query = " select distinct c.accountId from account c ", 
        resultClass = String.class)

the error message is

org.hibernate.MappingException: Unknown entity: java.lang.String

Any clues ? Thanks

like image 543
user595234 Avatar asked Mar 18 '12 22:03

user595234


2 Answers

@SqlResultSetMappings({
    @SqlResultSetMapping(name = "alertMapping", columns = {
        @ColumnResult(name = "accountId")})
})
@NamedNativeQuery(name = "alert", 
query = " select distinct c.accountId from account c ", 
        resultSetMapping = "alertMapping")

Usage:

EntityManager em = ...... / injected / etc
TypedQuery<String> query = em.createNamedQuery("alert", String.class);
List<String> accountIds = query.getResultList();

(unchecked syntax, but I hope the basic idea comes through)

For NamedNativeQueries you can only use resultClass when the result actually maps to an Entity. It's also possible to not specify a result mapping, in which case you'd get a List of Object[] back. Each element of the list would be one record, and you'd have to explicitly cast each Object to the type you wanted. Hm, the last part might only be available to NativeQueries and not Named - sorry unsure at the moment.

like image 107
esej Avatar answered Oct 01 '22 14:10

esej


Seems Hibernate only allows Entity result classes. Obviously not all JPA implementations have this restriction. DataNucleus JPA, for example, allows that query to run fine.

like image 22
DataNucleus Avatar answered Oct 01 '22 14:10

DataNucleus