SELECT Hibernate Polymorphic HQL Statement

I use Hibernate annotation to save my classes. I am currently using the following strategy to map classes

I have an abstract class, which is the parent class, and I have two subclasses that inherit its Mother, father.

I displayed it like this:

@MappedSuperclass public abstract class Parent { private int age; private String name; ... } 

And two other classes are declared as follows:

 @Entity public Class Father extends Parent { private boolean haveMustash; ... } 

Thus, basically the scenario is “Table for each class”.

Now I want to create a Hibernate HQL statement that will update the age of the parent, regardless of its type (mother, father). the parent will be scanned using a name column that is unique in both tables. but I don’t know, just looking at the name if it is Mother or Father. How can I create an HQL statement that will look in both tables and return the correct object for the update?

I thought of something like this: (but I have no idea if this is possible)

 Parent parent = hibernateTemplate.find("from Mother,Father where name=" + name); 
+6
source share
3 answers
 from Parent p where p.name = :name 

(not verified).

Note that if it works, this will lead to two queries, since both objects have nothing in common, except that they inherit some mapped attributes from the superclass. You do not have object inheritance here and do not execute a table for each class strategy. You would like Parent to be annotated using @Entity rather than @MappedSuperClass , and if you defined an inheritance strategy using @Inheritance .

+2
source

JB Nizet's answer is correct. Use @Entity to match the parent instead of @MappedSuperclass . This allows you to run Hibernate requests and updates on Parent (the latter allows you to run it only for father and mother). You can save the table in the class with the annotation @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) .

from Mother,Father will not work because it implicitly joins tables. What you want is union. Using @Entity , Hibernate will do this automatically.

+1
source

According to the Hibernate Reference, this works!

Several classes may appear, leading to a Cartesian product or “cross” union.

from Formula, Parameter

(see 14.2)

Hibernation reference

You can also search in both tables separately and then check which one is non-zero?

-1
source

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


All Articles