-1

I'm new and I have an assignment concerning JPA Criteria Queries. I'm trying to understand what exactly means this code.

EntityManager em = ...
CriteriaBuilder qb = em.getCriteriaBuilder();
CriteriaQuery<Person> c = qb.createQuery(Person.class);
Root<Person> p = c.from(Person.class);
Predicate condition = qb.gt(p.get(Person_.age), 20);
c.where(condition);
TypedQuery<Person> q = em.createQuery(c); 
List<Person> result = q.getResultList();

Can you please explain every line in detail and why these are the steps to follow? I found many resources online but still I can't get the full figure of it...

For example what's the meaning of: createQuery(Person.class)? Or the true difference between TypedQuery and a CriteriaQuery?

I've read what's the meaning of a query object from the blog of Martin Fowler: "A Query Object is an interpreter [Gang of Four], that is, a structure of objects that can form itself into a SQL query. You can create this query by refer-ring to classes and fields rather than tables and columns."

However it's written in a way that i still can't quite understand...

Thanks

Unearthly
  • 121
  • 6

1 Answers1

1
@Entity
public class Person {
    @Id
    Long id;
    String name;
    Integer age;

    //getters, setters, toString, hashcode, etc ...
}

Task: Create a query to get names of persons older than the given age


1. TypedQuery allows you to write JPQL queries manually.

EntityManager em;

public List<String> getNamesOfPersonsOlderThan(Integer minAge) {
    String jpql = "select p.name from Person p where p.age>:minAge";
    
    TypedQuery<String> query = em.createQuery(jpql, String.class);

    return query.setParameter("minAge", minAge).getResultList();
}

2. CriteriaQuery provides a programmatic way to define dynamic platform-independent typesafe queries

EntityManager em;

public List<String> getNamesOfPersonsOlderThan(Integer minAge) {

    //CriteriaBuilder is used to construct criteria queries, compound selections, expressions, predicates, orderings.
    CriteriaBuilder cb = em.getCriteriaBuilder();

    //Create a query returns String or List<String> as a result
    CriteriaQuery<String> query = cb.createQuery(String.class);

    //Create and add a query root corresponding to the given entity
    Root<Person> person = query.from(Person.class);

    //Create a predicate to select persons older than minAge
    Predicate condition = cb.gt(person.get(Person_.age), minAge);

    //Set the query selection and predicate
    query.select(person.get(Person_.name)).where(condition);

    //Pass the query to the entity manager and get the result
    return em.createQuery(query).getResultList();
}

Roughly the query looks like this from(Person).select(Person.name).where(Person.age > minAge)

Oleksii Valuiskyi
  • 2,691
  • 1
  • 8
  • 22