Hibernate: request objects by attributes of inherited classes

I am having a problem with Hibernate regarding requests to classes that use inheritance. Basically, I have 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 has already been set this way, and I cannot easily change it. As you can see ClassB1 and ClassB2 inherit from ClassA. Both classes contain a set of attributes that sometimes even have the same name (but I cannot transfer them to ClassA, since there are additional subclasses that do not use them). A record class refers to one instance of one of these classes.

Now my question is: I want to select all the record objects in my database that are related to an instance of ClassB1 or ClassB2, for example. P1300 field == 15.5 (so it can be instances of ClassB1 or ClassB2, since the P1300 attribute is declared in both classes).

What I tried looks something like this:

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

But since the P1300 is not an attribute of the ClassA sleep mode, it throws an exception telling me:

 could not resolve property: P1300 of: ClassA 

How can I say that hibernation should look in all subclasses to find the attribute that I want to filter?

Thanks MichaelD

+4
source share
2 answers

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

If there are other ancestors that do not have this property, then such a request does not make much sense - attributeSet may or may not have this property.

0
source

I do not have access to a good IDE to verify this, but you must first add and add an alias to your request.

Try adding:

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

I do not think that the problem is related to the hierarchy, but the lack of an alias in your request.

0
source

Source: https://habr.com/ru/post/1304257/


All Articles