views:

108

answers:

2

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

A: 

Since the property private Double P1300 appears in both subclasses, just pull it up to the parent class.

If there are other ancestors that don't have this property, then such a query doesn't make much sense - the attributeSet might, or might not have this property.

Bozho
Thank you for your answer. The problem is not only that some of the sub-classes don't have that attribute but also that ClassB1, ClassB2 etc. are added as "Plug-Ins". Which means I don't know which attributes are be there. But I have to be able to search for any recording object which has a certain attribute/value in the attributeSet. Usually I'd implement such an attributeSet as key/value table and not by subclassing ClassA, but as I said the class hierarchy is already given...
MichaelD
A: 

I don't have access to a good IDE to validate this but at first look you need to add and alias to your query.

Try to add:

criteria.createAlias("attributeSet", "attributeSet");

I don't think the problem is related to the hierarchy but the lack of alias in your query.

Manuel Darveau