• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Unable to cast result set into typed variable with Spring Data Native Named Query

 
Mike Cheung
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there I have a question with using Spring Data JPA. I don't like how all the examples are using List<Object[]> for native named queries. There is no type checking and makes the code harder to read. So I tried to type cast it to List<myType> instead.
The interesting bit is that the result set was created using this new type fine but the minute I try to use it via a for loop, it fails with the following.
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.EmployeeAddress

Snippet 1 - this works


Snippet 2 - this fails


The interesting bit is if I set a break point at the following line ...


The IDE shows that the variable queryResult13 is created as type List<EmployeeAddress>. However as soon as I look into the List, it shows that the elements were of type Object[] (same as what I'd get from snippet 1 above). Any idea?
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mike Cheung wrote:The interesting bit is that the result set was created using this new type fine but the minute I try to use it via a for loop, it fails with the following.
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.EmployeeAddress

That makes sense! As every element in your list is an Object array and not an EmployeeAddress. And remember that casting to a List with a generic type parameter, it's only casting the List instance and does not verify if each element matches the generic type parameter. And that's why the first lines in both code snippets will run without throwing a runtime exception.

If you want to get rid of the Object array when executing a native query, you can use a Result Set Mapping or a ConstructorResult. The latter one is only supported in JPA 2.1.

Hope it helps!
Kind regards,
Roel
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic