Java Reference
In-Depth Information
Query criteriaDel = em.createQuery(q);
} catch (NotSupportedException | RollbackException | SystemException |
HeuristicMixedException | HeuristicRollbackException ex) {
Logger.getLogger(CriteriaUpdates.class.getName()).log(Level.SEVERE, null, ex);
return null;
both the CriteriaUpdate and CriteriaDelete examples that we've demonstrated can be made more
type-safe by making use of the MetaModel api. For each entity class in a particular persistence unit, a metamodel class
is created with a trailing underscore, along with the attributes that correspond to the persistent fields of the entity class.
this metamodel can be used to managed entity classes and their persistent state and relationships. therefore, instead
of specifying an error prone String in the Path to obtain a particular attribute, you could specify the metamodel attribute
instead, as follows: e.get(Employee_.status)
For more information on using the MetaModel api to create type-safe queries, please refer to the online documentation.
The Criteria API can be very detailed, and it is also very powerful. To learn more about the Criteria API, please see
the documentation online at .
Downcasting in the FROM and WHERE clauses
The act of downcasting is defined as the casting of a base type or class reference to one of its derived types or classes.
The Java EE 7 platform introduces the concept of downcasting to JPA by providing the ability to obtain a reference to
a subclass of a specified entity within a query. In other words, you can explicitly query one or more entities and
retrieve the attributes from each of the entities as well as any attributes from entities that are subclasses of those that
are explicitly declared in the query. In order to provide this ability, the new TREAT keyword has been added to JPA.
The use of the TREAT operator is supported for downcasting within path expressions in the FROM and WHERE
clauses. The first argument to the TREAT operator should be a subtype of the target type, otherwise the path is
considered to have no value, attributing nothing to the end result. The TREAT operator can filter on the specified types
and subtypes, as well as perform a downcast.
The syntax for use of the TREAT operator is as follows:
SELECT b.attr1, b.attr2
FROM EntityA a JOIN TREAT(a.referenceToEntityB as EntityBType) b
In the above JPQL, the TREAT operator contains an attribute from the specified entity ( EntityA ) that relates to
a subtype ( EntityB ). The downcast takes place when attributes from EntityBType , a subclass of EntityB , are specified
within the SELECT clause. The TREAT operator performs the downcast and allows access to subtype entities.
The following lines of code demonstrate this technique in action. This method is taken from the class
org.javaee7.session.ProductSession , and it is used to obtain the name and color of WidgetA entities, which are
a sub-type of the Product entity.
Search WWH ::

Custom Search