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.
How can I select a POJO with a Criteria Quey similar to a JPQL query?
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.
You can see the definition of the constructor call in line 4. The construct(Class
Get this Hibernate Tip as a printable PDF!Join the free Thoughts on Java Library to get access to lots of member-only content, like a printable PDF for this post, lots of cheat sheets and 2 ebooks about Hibernate.
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.