I use Hibernate
v.4 (inside Spring MVC
). There are several inherited entities mapped on one table with SINGLE_TABLE
strategy using DiscriminatorColumn
:
@Entity
@DiscriminatorColumn
@DiscriminatorOptions(force = true)
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public abstract class A {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected Long id;
...
}
@Entity
@DiscriminatorValue(value = "B")
public class B extends A {
...
}
@Entity
@DiscriminatorValue(value = "C")
public class C extends A {
...
}
Consider I have universal GUI interface for managing this entities, so in input (say in HttpServletRequest
) I have only id
of the object, but I don't know which type exactly is this object; that is why I can not specify exact class for session.load(...)
. But for specific parts I need access to specific fields of entities, so I have to cast object to precise type (B
or C
).
So, when I'm doing A a = (A) session.load(A.class, id);
it constructs proxy object under type A
, so it can not be cast to B
or C
:
java.lang.ClassCastException: my.A_$$_jvst551_6 cannot be cast to my.B
The question: is any way how I can configure my entities or use special tricks to load entity from database and obtain object of precise type of which correspondence row presents?
Well, it's easy: I should use session.get(A.class, id)
instead of session.load(...)
.