开发者

Hibernate: Querying objects by attributes of inherited classes

开发者 https://www.devze.com 2022-12-22 21:51 出处:网络
I ran into a problem with Hibernate concerning queries on classes which use inheritance. Basically I\'ve the following class hierarchy:

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 = "Cl开发者_高级运维assB1" )
@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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号