In Hibernate, the Criteria Query API provides a flexible way to construct SQL-like queries. By default, the generated query retrieves all columns, which can lead to performance issues when certain columns are excluded.
To exclude a specific column from a Criteria Query, use projections. Projections allow you to specify the columns that should be included in the result.
<code class="java">CriteriaBuilder cb = session.getCriteriaBuilder(); CriteriaQuery<Object[]> criteriaQuery = cb.createQuery(Object[].class); Root<Entity> root = criteriaQuery.from(Entity.class); criteriaQuery.multiselect(root.get("id"), root.get("name"), root.get("description")); List<Object[]> result = session.createQuery(criteriaQuery).list();</code>
This query will retrieve only the id, name, and description columns, omitting other columns from the result.
When using projections, the result aliases must match the properties specified in the projection list. Otherwise, you may encounter errors like "Unknown column 'alias' in 'where clause'".
<code class="java">CriteriaBuilder cb = session.getCriteriaBuilder(); CriteriaQuery<Object[]> criteriaQuery = cb.createQuery(Object[].class); Root<Entity> root = criteriaQuery.from(Entity.class); criteriaQuery.multiselect(root.get("id").as("y0"), root.get("name").as("y1"), root.get("description").as("y2")); List<Object[]> result = session.createQuery(criteriaQuery).list();</code>
In this query, the aliases ("y0", "y1", "y2") match the order of the properties in the projection list.
The HQL equivalent of the Criteria Query with projections is:
<code class="hql">SELECT e.id, e.name, e.description FROM Entity e</code>
The above is the detailed content of How to Retrieve Specific Columns Using Hibernate Criteria Query?. For more information, please follow other related articles on the PHP Chinese website!