Andrei (1) [Avatar] Offline
#1
In Secion 6.4.1 you speak about some nuances of polymorphic many-to-one associations noting along, the way, that when such associations are mapped lazily there are limitations on the use of casting due to the use of proxies:

.. if BillingDetails was mapped with lazy="true", Hibernate would proxy the billingDetails association. In this case, we wouldnÂ’t be able to perform a typecast to the concrete class CreditCard at runtime, and even the instanceof operator would behave strangely:
User user = (User) session.get(User.class, uid);
BillingDetails bd = user.getBillingDetails();
System.out.println( bd instanceof CreditCard ); // prints "false"
CreditCard cc = (CreditCard) bd; // ClassCastException!


Then you propose a way of dealing with this isse, which is based on knowing the expected runtime type:

User user = (User) session.get(User.class, uid);
BillingDetails bd = user.getBillingDetails();
// Get a proxy of the subclass, doesn't hit the database
// The below code assumes the knowledge of the expected
// runtime type of the bd instance.

CreditCard cc = (CreditCard) session.load( CreditCard.class, bd.getId() );
expiryDate = cc.getExpiryDate();

What you don't explain is how to dynamically figure out the runtime type of a given BillingDetails object. Consider this code:

User user = (User) session.get(User.class, uid);
BillingDetails bd = user.getBillingDetails();
// Suppose I don't know what dynamic type of the bd POJO is.
// Depending on the runtime type, I'd like to use different execution paths:
if (bd instanceof CreditCard) {
// process bd as a credit card;
}
else if (bd instanceof BankAccount) {
// process bd as a bank account;
}

Does Hibernate support this usage scenario for lazy associations?

Thanks in advance,
Andrei.