I've been trying to find a JPA Criteria API tutorial but haven't been much successful. Do you know about any for beginners? I'd like to start using it in an Java5/Maven app to build complex search queries.
Asked
Active
Viewed 8.2k times
69
-
4Correlation coefficient between off-topic and usefulness == 1.0 – Dave Nov 29 '14 at 23:55
4 Answers
105
The Dynamic, typesafe queries in JPA 2.0 article is a very good one on this topic, actually the best one I've found so far online, even better than the Chapter 23 Using the Criteria API to Create Queries from the Java EE 6 tutorials (that contains some mistakes).

Pascal Thivent
- 562,542
- 136
- 1,062
- 1,124
-
2@HDave Oracle's EE7 link to the Criteria API has changed to [https://docs.oracle.com/javaee/7/tutorial/persistence-criteria.htm#GJITV](https://docs.oracle.com/javaee/7/tutorial/persistence-criteria.htm#GJITV) – skomisa Jan 03 '15 at 16:04
14
Examples of common queries are here
All examples are in this form:
CriteriaBuilder cb = em.getCriteriaBuilder();
// Query for a List of objects.
CriteriaQuery cq = cb.createQuery();
Root e = cq.from(Employee.class);
cq.where(cb.greaterThan(e.get("salary"), 100000));
Query query = em.createQuery(cq);
List<Employee> result = query.getResultList();
If you are also considering other technologies you should seriously consider querydsl. Main advantages over criteria include shorter code, good readability and similar syntax to regular sql.
Example QueryDSL code here:
JPAQuery query = new JPAQuery(entityManager);
List<Person> persons = query.from(person)
.where(
person.firstName.eq("John")),
.list(person);

Marcin Szymczak
- 11,199
- 5
- 55
- 63
-
1your first example throws "No explicit selection and an implicit one could not be determined " exeption – Irakli Dec 03 '16 at 09:10
-
7
Pro JPA 2: Mastering the Java Persistence API http://books.google.com/books?id=j84hdeHH2PYC
This is the source I find the most useful.

John Manak
- 13,328
- 29
- 78
- 119