Hi Guys, I am back with another post titled “Using Projections in Hibernate”. When we deal with large objects(containing multiple attributes) we use Projections to select only a subset of attributes of an object. It helps in avoiding unnecessary column reads thus reducing memory consumption and processing time.

Many people get confused between hibernate projections and criteria. Remember, both are not mutually exclusive, we can use both at the same time. Projections are actually used in the context of Criteria. We can use Projections to specify distinct clauses and use aggregate functions like count, avg, max, sum etc. It is like referring to which data we want to fetch like we modify the select clause in an SQL query.

The difference between Criteria and Projection is the HOW and WHICH. Hibernate Criteria is the HOW (How we are fetching the data by applying various conditions). Projections specify which data we would like to fetch.

The example below shows how we can select only a subset of an object:-

 Criteria cr = session.createCriteria(Company.class)
      .add(Projections.property("id"), "id")
      .add(Projections.property("Name"), "Name"))    .setResultTransformer(Transformers.aliasToBean(Company.class));

  List<Company> list = cr.list();

The above Class named “Company” may contain several attributes but we are only interested in “id” and “Name” attribute.

Following are the examples that covers various scenarios in which Projections can be useful:-

Criteria cr = session.createCriteria(Galaxies.class);

// total row count.

// To get average of a field.

// To get distinct count of a field.

// To get maximum of a field.

// To get minimum of a field.

// To get sum of a field.

To get the result of the aggregate functions we can use the following:-

// Integer Value
Integer varName= (Integer) cr.uniqueResult();

Double varName= (Double) cr.uniqueResult();

That was all about Hibernate Projections.
Thanks 🙂