Hibernate Tips: How to select a POJO with a Criteria Query


Take your skills to the next level!

The Persistence Hub is the place to be for every Java developer. It gives you access to all my premium video courses, monthly Java Persistence News, monthly coding problems, and regular expert sessions.


Hibernate Tips is a series of posts in which I describe a quick and easy solution for common Hibernate questions. If you have a question you like me to answer, please leave a comment below.

Question:

How can I select a POJO with a Criteria Quey similar to a JPQL query?

Solution:

You can use a similar constructor expression with the Criteria API as you use in JPQL queries. The following code snippet shows an example of it.

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery q = cb.createQuery(AuthorValue.class);
Root root = q.from(Author.class);
q.select(cb.construct(AuthorValue.class, root.get(Author_.firstName), root.get(Author_.lastName)));

List authors = em.createQuery(q).getResultList();

You can see the definition of the constructor call in line 4. The construct(Class resultClass, Selection… selection) method of the CriteriaBuilder tells your JPA implementation to call the constructor of the AuthorValue class with a set of parameters. It does that for each record of the result set. In this example, I use the JPA Metamodel to reference the first name and last name as constructor parameters.

Learn More:

If you don’t want to create a POJO to represent your query result, you can also select a set of scalar values. You can learn more about it in my Hibernate Tip: How to select multiple scalar values in a Criteria Query.

And if you want to learn more about creating type-safe, programmatic queries with the Criteria API, you should have a look at my Advanced Hibernate Online Training. It has a whole module about the Criteria API and I also show other, advanced options to query your data.

Hibernate Tips Book

Get more recipes like this one in my new book Hibernate Tips: More than 70 solutions to common Hibernate problems.

It gives you more than 70 ready-to-use recipes for topics like basic and advanced mappings, logging, Java 8 support, caching, and statically and dynamically defined queries.

Get it now!

3 Comments

  1. Avatar photo Luiz Jacó says:

    How can I select a pojo with a list attribute?

    Person Entity:

    private Long id;

    private List phones;

    1. Avatar photo Thorben Janssen says:

      You can’t select a POJO projection that contains a List of attributes. You can do 2 things:

      1. Select the POJO without the List and execute an additional query for each POJO to get the List. This creates an n+1 select issue and only works, if you don’t select too many POJOs.
      2. Select all required information in 1 query and provide your own code to map these records to the POJO.
  2. Avatar photo royal loucia says:

    it was helpfull

Comments are closed.