Hibernate: Querying objects by attributes of inherited classes

Posted by MichaelD on Stack Overflow See other posts from Stack Overflow or by MichaelD
Published on 2010-03-16T13:15:27Z Indexed on 2010/03/16 13:16 UTC
Read the original article Hit count: 280

Filed under:
|
|

Hi all,

I ran into a problem with Hibernate concerning queries on classes which use inheritance. Basically I've the following class hierarchy:

@Entity 
@Table( name = "recording" ) 
class Recording 
{    
  ClassA attributeSet;
  ...
}

@Entity
@Inheritance( strategy = InheritanceType.JOINED )
@Table( name = "classA" )
public class ClassA
{
  String Id;
  ...
}

@Entity
@Table( name = "ClassB1" )
@PrimaryKeyJoinColumn( name = "Id" )
public class ClassB1 extends ClassA
{
  private Double P1300;
  private Double P2000;
}

@Entity
@Table( name = "ClassB2" )
@PrimaryKeyJoinColumn( name = "Id" )
public class ClassB2 extends ClassA
{
  private Double P1300;
  private Double P3000;
}

The hierarchy is already given like this and I cannot change it easily. As you can see ClassB1 and ClassB2 inherit from ClassA. Both classes contain a set of attributes which sometimes even have the same names (but I can't move them to ClassA since there are possible more sub-classes which do not use them). The Recording class references one instance of one of this classes.

Now my question: What I want to do is selecting all Recording objects in my database which refer to an instance of either ClassB1 or ClassB2 with e.g. the field P1300 == 15.5 (so this could be ClassB1 or ClassB2 instances since the P1300 attribute is declared in both classes).

What I tried is something like this:

Criteria criteria = session.createCriteria(Recording.class);
criteria.add( Restrictions.eq( "attributeSet.P1300", new Double(15.5) ) );
criteria.list();

But since P1300 is not an attribute of ClassA hibernate throws an exception telling me:

could not resolve property: P1300 of: ClassA

How can I tell hibernate that it should search in all subclasses to find the attribute I want to filter?

Thanks MichaelD

© Stack Overflow or respective owner

Related posts about java

Related posts about hibernate