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.
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.
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.
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.
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();
You can use Path type method as documented here:
Predicate p = cb.equal(e.type(), cb.literal(Entity.class));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With