Wednesday, March 10, 2010

Hibernate, lazy loading and inheritance

A common problem with typecasting a lazy loaded entity to its child is a ClassCastException. This exception occurs because the dynamic created proxy implements the baseclass and has no knowledge about its subclasses.

Suppose we have a class B which extends A and a class C which has class A as a member as shown below.

public class A
{
   private Long id;
   private String name;
   public String getName() { return name; }
   public void setName(String name) { this.name = name; }
   public Long getId() { return id; }
}

public class B extends A
{
   private String somethingElse;
   public String getSomethingElse() { return somethingElse; }
   public void setSomethingElse(String something) { this.somethingElse = something; }
}

public class C
{
   private Long id;
   private A a;
   public A getA() { return a; }
   public void setA(A a) { this.a = a; }
   public Long getId() { return id; }
}

Read more: blog.smart-java.nl  

Posted via email from jasper22's posterous