Reputation: 1558
I'm running a database query and trying to cast the result to a Customer object, but I'm getting an error saying:
java.lang.ClassCastException: Entities.Customer cannot be cast to Entities.Customer
My code:
Customer c = (Customer)em.createNamedQuery("Customer.findByEmail")
.setParameter("email", user)
.getSingleResult();
I've read that this is due to classloaders, but to be honest it's a bit over my head. Is there a huge issue somewhere else, or am I just casting it incorrectly?
Upvotes: 0
Views: 2759
Reputation: 73528
It looks like you have 2 ClassLoaders involved. You can check the classloaders with
Customer.class.getClassLoader();
em.createNamedQuery("Customer.findByEmail").setParameter("email", user).getSingleResult().getClass().getClassLoader();
Then you can try to find more information.
Upvotes: 3
Reputation: 1780
Like allprog said it is because the class that is being given back to you comes from a different jar than the one of your webapp (I'm assuming you are working on a webapp).
At runtime, your Customer loaded by the class loader from one jar (or your app) is cast into the customer from an other jar (or app).
So different possibilities:
In both cases you get the same error.
you can try to decompile your classes using javap to see what happens.
If you want to know more about classLoading: http://zeroturnaround.com/rebellabs/video-do-you-really-get-class-loaders-a-jazoon-talk-by-jevgeni-kabanov/
Upvotes: 0
Reputation: 1615
If you have a choice, I would suggest using JPA 2.0 and use:
<T> TypedQuery<T> createNamedQuery(java.lang.String name,
java.lang.Class<T> resultClass)
I think it should avoid class cast exception.
Upvotes: 0