JPA2 Criteria Builder - queries on abstract classes and several subclasses

First of all, sorry if this question has already been asked, but I could not find any similar questions and answers for my problem.

My problem is that I have several subclasses at several levels of the hierarchy, inherited from one subclass.

@Entity public class A{ } @Entity public class B extends A { ... } @Entity public class C extends A{ ... } @Entity public class D extends C { private String someAttribute; } @Entity public class E extends C { private String anotherAttribute; } 

I need to process a request for C and get all entities from C,D,E according to my criteria, which refer to attributes from D and E

I noticed that it is impossible to access, for example, someAttribute fro D executing a request in C eg:

 Root root = query.from(C.class); Path p = root.get("someAttribute"); Path p2 = root.get("anotherAttribute"); 

Please note that I cannot work with metamodels at this stage.

In JPAQL, I would encode something like this:

 `select e1 from C eq where someAttribute = .... or anotherAttribute = ....` 

And this will correctly resolve my hierarchy.

To solve the problem, I created my own annotation equivalent to @XmlSeeAlso and named it @PersistenceSeeAlso which tells me which subclasses I need to find in order to find my attribute. So when I process my accoridng hierarchy to @PersistenceSeeAlso and get my paths, I need to create a new Root element for each subclass that I am looking for for my attribute.

The main problem is that query.form(clazz) creates a connection in the request, which completely changes my request, but I need a Root element for my type to resolve the path.

So my question is; Is there a way to handle multiple subclasses using JPA2 CriteriaBuilder without creating new Root instances, possibly with EntityType?

Or am I doing something completely wrong?

Thank you in advance!

Regards, Question

+4
source share
1 answer

Sorry for the long wait!

This is a big question that I see all the time. The problem is that you accept C subtype information, which is not entirely correct.

If you use the inheritance strategy "table for each class" or "joined table", the data for D and E is stored in separate tables, and select e1 from C eq where someAttribute = .... or anotherAttribute = .... will not work since these columns do not exist in C.

You will NEED TO JOIN the columns from D and E to C before you can filter. (I answered a similar question before this helps.

+1
source

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


All Articles