Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the JPA CriteriaBuilder way for filtering on Sub Classes?

JPA 2.0 provided a means to filter by subclass using the JPQL expressions TYPE, for example :

SELECT e
FROM entity e
WHERE TYPE(e) = :entityType

where parameter entityType would be the value of the discriminator column.

What is the recommended way for achieving the same thing with the JPA criteria builder, considering the discriminator column appears to be off limits?

I'm using JPA 2.1 and so far the only solution that seems adequate is mapping the discriminator column as a read only field within the Java entity, but I'm not sure if this is a supported feature.

like image 927
Grant Lay Avatar asked Apr 04 '16 09:04

Grant Lay


People also ask

What is CriteriaBuilder in JPA?

EntityManager instance is used to create a CriteriaBuilder object. CriteriaQuery instance is used to create a query object. This query object's attributes will be modified with the details of the query. CriteriaQuery. from method is called to set the query root.

What is CriteriaBuilder in hibernate?

public interface CriteriaBuilder. Used to construct criteria queries, compound selections, expressions, predicates, orderings. Note that Predicate is used instead of Expression<Boolean> in this API in order to work around the fact that Java generics are not compatible with varags. Since: Java Persistence 2.0.

How do I find query in CriteriaBuilder?

Create an instance of Session from the SessionFactory object. Create an instance of CriteriaBuilder by calling the getCriteriaBuilder() method. Create an instance of CriteriaQuery by calling the CriteriaBuilder createQuery() method. Create an instance of Query by calling the Session createQuery() method.


Video Answer


2 Answers

Examples of common queries are here

Example:

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery();
Root e = cq.from(Entity.class);
cq.where(cb.equal(e.type(), entityType));
Query query = em.createQuery(cq);
List<Entity> result = query.getResultList();
like image 144
ooozguuur Avatar answered Oct 12 '22 11:10

ooozguuur


You can use Path type method as documented here:

Predicate p = cb.equal(e.type(), cb.literal(Entity.class));
like image 29
Matteo Baldi Avatar answered Oct 12 '22 10:10

Matteo Baldi