1

I have an en Entity A which is super class for entities B and C, A is annotated with @Inheritance(strategy = InheritanceType.JOINED).

Then another Entity X which has relation to A.

I set x.a with some object of type B, but when I load x, and check type for x.a it is A, and I cannot cast it to B.

I did that a lot of mapping like this before and it was working correctly cannot know what is the problem here.

Also when I do entityManager.find(A.class, id), it also return A although there is an entity B with the same id, it returns B when I run it from Junit test but not when run the application on tomcat server.

Noura
  • 722
  • 10
  • 24

2 Answers2

1

Sounds like you may be getting a proxy instead of the actual instance which is why you can't cast to the subclass. The following may help you unwrap the proxy:

Converting Hibernate proxy to real object

Community
  • 1
  • 1
Abdullah Jibaly
  • 53,220
  • 42
  • 124
  • 197
0

You will encounter this problem in connection with the lazy-loading mechanism of Hibernate. Hibernate wraps each object that is lazily loaded into a so-called proxy object. Your object x.a will be of type HibernateProxy, when you load x from database.

I've found this solution useful (similar to @Abdullah's).

How to unproxy a hibernate object

You could also eagerly fetch the relation x.a to avoid this problem, hence there won't be a proxy-object created.

Community
  • 1
  • 1
matthaeus
  • 797
  • 2
  • 7
  • 17