I am currently using criteria to retrieve the details of a user, but when trying to query the details object with the right user, I get a ClassCastException.
My Criteria Code;
Criteria criteria = sess.createCriteria(UserDetails.class)
criteria.add(Restrictions.eq("user.id", user.id));
I also tried using;
Criteria criteria = sess.createCriteria(UserDetails.class)
Criteria subCriteria = criteria.createCriteria("user");
subCriteria.add(Restrictions.eq("id", user.id));
Both give me the ClassCastException. I know I can easily solve it by letting the User implement Serializable, but is there any other solution?
The only other solution is to implement Externalizable.
You should implement Serializable
interface.
For me, the problem was a bug in Hibernate when using non-pk relations: https://hibernate.atlassian.net/browse/HHH-7668
As a workaround, I implemented Serializable and the exception is gone
My experience was this. I had a chain of parent/child relationships working. Then, I was forced to refactor. During the process, I failed to update all my annotations correctly. That is when I started receiving the cast to Serializable error. I implemented Serializable, and this exposed the real problems. Once everything was working, I was able to remove Serializable.
So, in answer to your question, the real problem may be in your setup, and Hibernate is trying to work around the issues by serializing certain entities. Try temporarily implementing Serializable to expose the issues, and then removing it.
来源:https://stackoverflow.com/questions/4525186/cannot-be-cast-to-java-io-serializable