Home >Database >Mysql Tutorial >How Do I Select Specific Columns in Hibernate Criteria Queries?
Hibernate Criteria Query: Selecting Specific Columns
In Hibernate Criteria Query, the default behavior is to retrieve all columns from the specified table. However, it is possible to exclude certain columns from the query results for performance optimizations.
Projections for Column Selection
To exclude a column from the query results, projections can be used. Projections allow you to specify a list of properties that should be returned. By explicitly listing the desired properties, the remaining columns will be excluded.
Criteria Query Example
Consider the following SQL query:
<code class="sql">SELECT user.id, user.name FROM user;</code>
To achieve the same result using Hibernate Criteria Query, one can use the following code:
<code class="java">CriteriaBuilder cb = session.getCriteriaBuilder(); CriteriaQuery<Tuple> cq = cb.createTupleQuery(); Root<User> root = cq.from(User.class); cq.multiselect(root.get("id"), root.get("name"));</code>
In this example, cb, cq, and root are builder objects that facilitate query construction. The multiselect() method is used to specify the columns to be returned.
Handling Projections in HQL
The HQL equivalent of the above Criteria Query would be as follows:
<code class="hql">SELECT id, name FROM User</code>
By using projections, it is possible to optimize queries and reduce the amount of data retrieved from the database.
The above is the detailed content of How Do I Select Specific Columns in Hibernate Criteria Queries?. For more information, please follow other related articles on the PHP Chinese website!