45

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?

Thizzer
  • 16,153
  • 28
  • 98
  • 139

4 Answers4

48

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

m1schka
  • 957
  • 1
  • 9
  • 10
  • This is saved my time, I don't need to find any other way then for now :) – Al-Mothafar Dec 11 '18 at 13:22
  • 2
    Is this a way to solve the issue or it just suppresses the error? Sorry, I'm new to spring Jpa and was trying to join tables with non-primary keys. – elembivos Aug 18 '19 at 14:31
35

You should implement Serializable interface.

user207421
  • 305,947
  • 44
  • 307
  • 483
16

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.

Steve11235
  • 2,849
  • 1
  • 17
  • 18
  • 4
    In my case it was a `ManyToOne` mapping which had more than one result in a query which produced the `ClassCastException`. Hibernate created a proper Exception after `implements Serializable`. – adrobisch Jun 17 '15 at 10:26
  • In my case, the interface makes it work, but I don't want to have to add it in when I am using hibernate to marshal/unmarshal. – Robin Jun 22 '15 at 14:24
  • 1
    I tried implementing and everything works fine. Though i can't understand why is it needed as other entities are working fine without implementing `Serializable` . – Nikhil Sahu Feb 06 '17 at 10:02
7

The only other solution is to implement Externalizable.

user207421
  • 305,947
  • 44
  • 307
  • 483