Video in progress
What is the JPA static metamodel (`Order_`), and why use it when working with the Criteria API?
The static metamodel is an Order_ class that an annotation processor generates for each entity at compile time, with the attributes as typed constants. In Criteria you write Order_.status instead of the string "status": if a field name changes, the error shows up at compile time, not at runtime.
📖 Answer
Criteria written with strings:
cb.equal(root.get("staus"), Status.NEW); // wrong name: fails only when the query runs
With the metamodel:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Order> q = cb.createQuery(Order.class);
Root<Order> o = q.from(Order.class);
Join<Order, Customer> c = o.join(Order_.customer);
q.where(cb.equal(o.get(Order_.status), Status.NEW),
cb.like(c.get(Customer_.name), "Ali%"));
The type of o.get(Order_.status) is Path<Status>, so a type mistake like cb.equal(..., "NEW") shows up in the IDE too. During refactoring (status → state), the compiler points out every place.
To enable it, you add an annotation processor to the build:
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-jpamodelgen</artifactId>
<scope>provided</scope>
</dependency>
In newer Hibernate versions this module was renamed hibernate-processor, and it can also generate typed query methods.
The metamodel is used in Spring Data Specifications too: (root, q, cb) -> cb.equal(root.get(Order_.status), s). The generated classes end up in target/generated-sources, so don't commit them to git.
The only downside is an extra step in the build. If the project has no Criteria at all and every query is written with @Query, the metamodel doesn't help much; there, validating the HQL at startup is enough.
Sign up to mark studied questions and save your progress.