Java Reference
In-Depth Information
System.out.println("result
:"+em.createNamedQuery("runtimeNamedQuery").getResultList());
The Criteria API
JPA since Version 2.0 offers two options for defining queries on entities. The first op-
tion is the JPQL which is a query language based on SQL. The second option is the
Criteria API where a query is constructed essentially with Java objects, as shown in
the following code:
EntityManagerFactory emf
=Persistence.createEntityManagerFactory("chapter04PU");
EntityManager em = emf.createEntityManager();
//create entity manager
//criteria builder declaration
CriteriaBuilder cb = em.getCriteriaBuilder();
//declaration of the object that will be
returned by the query
CriteriaQuery<Student> cq =
cb.createQuery(Student.class);
//Declaration of the entity to which the
request is made
Root<Student> student = cq.from(Student.class);
//Query construction
cq.select(student).where(cb.greaterThan(student.<String>get("id"),
"123"));
TypedQuery<Student> tq = em.createQuery(cq);
//execution of the query
System.out.println("result :
"+tq.getResultList());
//JPQL equivalent query
SELECT a FROM Student a WHERE a.id > 123
Given that the two solutions do not evolve at the same rate, the major changes in the
Criteria API are support for bulk update/delete and new reserved identifiers.
Search WWH ::




Custom Search