Hibernate Tips: How to Select Multiple Scalar Values in a Criteria Query

DZone 's Guide to

Hibernate Tips: How to Select Multiple Scalar Values in a Criteria Query

Learn how to select multiple scalar values in a criteria query.

· Database Zone ·
Free Resource

Hibernate Tips is a series of posts in which I describe a quick and easy solution for common Hibernate questions. Some of the most popular tips are also available as a book.

If you have a question for a future Hibernate Tips post, please leave a comment below.


How can I select a list of scalar values in a Criteria query?


The CriteriaQuery interface provides the multiselect() method which allows you to select multiple scalar values. The following code snippet shows an example for such a query.

// Prepare query
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Tuple> q = cb.createTupleQuery();
Root<Author> author = q.from(Author.class);

// Select multiple scalar values
q.multiselect(author.get(Author_.firstName).alias("firstName"), author.get(Author_.lastName).alias("lastName"));

List<Tuple> authorNames = em.createQuery(q).getResultList();

for (Tuple authorName : authorNames) {
log.info(authorName.get("firstName") + " " + authorName.get("lastName"));

The multiselect() method expects a List or an array of Selection interfaces, which defines the entity attributes that will be fetched from the database. In this example, I use the JPA metamodel to reference the attributes in a type-safe way. When you execute such a CriteriaQuery, it returns a List of Tuple interface implementations. The Tuple interface provides convenient access to the selected values based on its position or its alias. In the code snippet, I defined an alias for each attribute in the query and use it to get them from the Tuple result.

database ,database tutorial ,hibernate ,hibernate tips ,hibernate tutorial ,jpa ,scalar values ,tutorial

Published at DZone with permission of Thorben Janssen , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}