(NOT FINISHED)
Create query defining objects with Java programming language APIs, are type safe and portable.
Also based on the abstract schema of persistent entities and closely related to JPQL.
Usage:
EntityManager em = ...;
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Pet> cq = cb.createQuery(Pet.class);
Root<Pet> pet = cq.from(Pet.class);
cq.select(pet);
TypedQuery<Pet> q = em.createQuery(cq);
List<Pet> allPets = q.getResultList();
Entity
Metamodel
package com.example;
...
@Entity
public class Pet {
40-2 The Java EE 7 Tutorial
Using the Metamodel API to Model Entity Classes
@Id
protected Long id;
protected String name;
protected String color;
@ManyToOne
protected Set<Person> owners;
...
}
package com.example;
...
@Static Metamodel(Pet.class)
public class Pet_ {
public static volatile SingularAttribute<Pet, Long> id;
public static volatile SingularAttribute<Pet, String> name;
public static volatile SingularAttribute<Pet, String> color;
public static volatile SetAttribute<Pet, Person> owners;
}
Metamodel class is generated for managed entities in a persistence unit. The name is entity class plus "_", with attributes corresponding to the persistent fields.
To obtain at development time, use persistence provider's annotation processor. This involves specific tools according to the tools and environment. For Eclipse / Hibernate, see environment doc.
To obtain at run time is uncommon, doesn't allow type-safe and doesn't allow to call persistent field or property names on metamodel class. Samples given in tutorial.
javax.persistence.criteria.CriteriaBuilder is used to construct:
Criteria queries
CriteriaBuilder.createQuery (group of methods) - example: cb.createQuery(Pet.class)
ROOT (correspond to FROM clause)
Root<Pet> pet = cq.from(Pet.class)
Root<Pet> pet = cq.from(Pet_) - using meta model
obtain multiple root instances - similar to multiple results in FROM
JOIN - Join<Pet, Owner> owner = pet.join(Pet_.owners)
chained JOIN - Join<Owner, Address> address = cq.join(Pet_.owners).join(Owner_.addresses)
Path navigation (used in SELECT and WHERE)
selections
expressions
predicates
ordering
obtain: EntityManager.getCriteriaBuilder()