This piece of code irritates me, sometimes it working and some other times it doesn\'t !
The NamedQuery : (name = \"User.findByLogin\", query = \"SEL
My guess would be that you have different classloaders. The same class loaded in a different classloader is still considered different by the JVM.
To verify this, you could try to catch the exception and print/log the classloaders.
public User findByLogin(String login) {
Query query = em.createNamedQuery("User.findByLogin");
query.setParameter("login", login);
Object result = null;
try {
result = query.getSingleResult();
return (User) result ;
} catch (javax.persistence.NoResultException ex) {
return null;
} catch (ClassCastException ex) {
logger.info("Object classloader: " + result.getClass().getClassLoader());
logger.info("Target class classloader: " + User.class.getClassLoader());
if(result.getClass().getClassLoader() != User.class.getClassLoader()) {
logger.warn("Different classloaders detected!");
}
}
}
As for the solution, that of course depends on the rest of your setup... To get you started, I can give you some pointers to related questions asked before. Maybe some of the answers there can be helpful to you:
Some of the suggested solutions include changing your classloader setup, using a common interface, or serializing/deserializing your object.