JPA Criteria Tutorial

JavaJpaAnnotationsJpa 2.0

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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).

Solution 2 - Java

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);

Solution 3 - Java

Pro JPA 2: Mastering the Java Persistence API http://books.google.com/books?id=j84hdeHH2PYC

This is the source I find the most useful.

Solution 4 - Java

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohn ManakView Question on Stackoverflow
Solution 1 - JavaPascal ThiventView Answer on Stackoverflow
Solution 2 - JavaMarcin SzymczakView Answer on Stackoverflow
Solution 3 - JavaJohn ManakView Answer on Stackoverflow
Solution 4 - JavaAaron SaundersView Answer on Stackoverflow