Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

Compliant Database DevOps: Deliver software faster while keeping your data safe. This new whitepaper guides you through 4 key ways Database DevOps supports your data protection strategy. Read free now

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.

Question

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

Solution

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.

Read this new Compliant Database DevOps whitepaper now and see how Database DevOps complements data privacy and protection without sacrificing development efficiency. Download free.

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

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}