Access Subclass Properties in Criteria Builder JPA

I am trying to use a JPA 2.0 criteria query with a basic Hibernate implementation. I'm having problems trying to access subclass properties in a where clause.

The following is a brief description of the facilities:

- Class A (which is a Entity & a Table by itself) - Class B (which is a Entity & a Table by itself) - Class A has OneToMany relationship with B - Class AB & BA are child classes of B (Both are entities but are not mapped to any tables. It holds few properties specific to it.) - Let us suppose both classes AB & BA has a property '''symbol''' 

Now the criteria are requested:

 CriteriaBuilder qb = futuresEntityManager.getCriteriaBuilder(); CriteriaQuery<A> query = qb.createQuery(A.class); Root<A> a = query.from(A.class); Join<A,B> b = a.joinSet("aLegs", JoinType.INNER); 

Now when I form the predicates:

 predicate=qb.and(qb.equal(a.get("id").get("accountId"), "1234")); predicate=qb.and(predicate,b.get("symbol").in(input.getSymbol())); 

----- The above line does not work at runtime, since b does not hold the reference to the character. only child classes AB and BA contain it.

How do I access the properties of child classes in this request? I have to include AB and BA for the character predicate.

Can someone help me solve this problem?

+4
source share
1 answer

You need to use JPA 2.0 Epression#as() :

 Path bCasted = (Path)b.as(AB.class); Predicate newCastedPredicate = bCasted.get("symbol").in(input.getSymbol()); 

But I think that you need to perform the operation described above separately and recursively for each of the necessary subclasses.

Unrelated: note that the in predicate accepts either a collection or an expression. Take a look at javadoc on the page above.

0
source

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


All Articles