Return Request Class for JPA

In JPA, I defined my own sql, which will return a String,

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

error message

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

Any clues? Thanks

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

Using:

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

(unchecked syntax, but I hope the main idea comes)

For NamedNativeQueries, you can use resultClass only when the result is actually mapped to Entity. It is also possible not to specify a comparison of results, in which case you will get the List object [] back. Each list item will be a single entry, and you will need to explicitly point each object to the type that you need. Hm, the last part may be available only for NativeQueries, not Named - sorry, unsure at the moment.

+17
source

Hibernate seems to only allow Entity result classes. Obviously, not all JPA implementations have this limitation. DataNucleus JPA , for example, allows this query to work fine.

+2
source

In my case, I changed the version of sleep mode from 3.5.6 to 4.3.3. It works fine.

 <!-- <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>3.5.6-Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>3.5.6-Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-annotations</artifactId> <version>3.5.6-Final</version> </dependency> --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.3.3.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.3.3.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>4.3.3.Final</version> </dependency> 
+1
source

Do not include resultClass in the request declaration

0
source

Source: https://habr.com/ru/post/1402143/


All Articles