hibernate

Hibernate Projections Tutorial

In hibernate; developers can implement the Projection interface to read the partial entity or entities from the relational database. In this tutorial, we will explore the use of Projection interface available in the org.hibernate.criterion package of the Hibernate framework.
 
 
 
 
 
 
 
 
 
 

1. Introduction

  • Object-Relational Mapping or ORM is the programming technique to map application domain model objects to the relational database tables
  • Hibernate is a Java-based ORM tool that provides the framework for mapping application domain objects to the relational database tables and vice versa. It provides the reference implementation of Java Persistence API that makes it a great choice as an ORM tool with benefits of loose coupling
  • A Framework that an option to map plain old Java objects to the traditional database tables with the use of JPA annotations as well as XML based configuration

Hibernate Projections - Hibernate Overview
Fig. 1: Hibernate Overview

1.1 Hibernate Annotations

  • Hibernate annotations are the newest way to define mappings without the use of a XML file
  • Developers use annotations to provide metadata configuration along with the Java code. Thus, making the code easy to understand
  • XML provides the ability to change the configuration without building the project. Thus, annotations are less powerful than the XML configuration and should only be used for table and column mappings
  • Annotations are preconfigured with sensible default values, which reduce the amount of coding required. For e.g., Class name defaults to Table name and Field names default to Column names

1.2 Hibernate Criteria

Hibernate Criteria Query language allow the developers to fetch the data from the relational database. The Criteria interface define several methods to specify the criteria and the object can be obtained by calling the createCriteria() method of the Session interface. The syntax for this method is.

public Criteria createCriteria(Class c)

Following points support the Criteria API in the Hibernate framework,

  • Safe from SQL injection
  • Supports pagination
  • Promote easy and cleaner queries
  • Helps compile-time checking
  • Perform only select query operations

1.3 Projections in Hibernate

Projection interface in the org.hibernate.criterion package is used in Hibernate framework to query the particular columns from the database. In the same package, Projections class is responsible for producing the projection objects. In this class, each method is static in nature and returns the projection interface object. Following points support the Projection interface in the Hibernate framework,

  • Projection is applied to the Criteria query object
  • The projection class provides some inbuilt functions like sum, max, min, rowCount etc to perform the aggregation operations in hibernate
  • If a developer wants to add a projection object to the criteria object, then he or she needs to call the criteria.setProjection(projection_obj) method
  • If a developer wants to read multiple columns from the database, then he or she needs to add the ProjectionList object to the setProjection() method i.e. criteria.setProjection(projection_list_obj)

Following snippet illustrate the use of the projection in hibernate criteria.

Code Snippet

// creating the criteria object.
Criteria myCriteria = session.createCriteria(Employee.class);

// creating the projection object.
Projection myProjection = Projections.property("employee_name");

// adding the projection object to the criteria object.
myCriteria.setProjection(myProjection);

List list = myCriteria.list();

1.3.1 Aggregation using Projections

Following methods are available in the Projections class to support the property aggregation in the hibernate framework.

  • sum(String property_name): Calculates the sum total of the property values
  • avg(String property_name): Calculates the average of the property’s value
  • count(String property_name): Count the number of times a property appears
  • countDistinct(String property_name): Count the number of unique values the property contains
  • max(String property_name): Calculates the maximum value
  • min(String property_name): Calculates the minimum value
  • rowCount(): Calculates the total number of records in the database table

1.3.2 Grouping records using Projections

Projections class provide the groupProperty(property_name) method for grouping the records. Following snippet illustrate the use of groupProperty() method.

Code Snippet

// creating the criteria object.
Criteria myCriteria = session.createCriteria(Employee.class);

// adding the 'groupProperty(property_name)' to the criteria object.
myCriteria.setProjection(Projections.groupProperty("designation"));

List results = myCriteria.list();

1.4 Download and Install Hibernate

You can read this tutorial in order to download and install Hibernate in the Eclipse IDE.

1.5 Download and Install MySQL

You can watch this video in order to download and install the MySQL database on your Windows operating system.

Now, open up the Eclipse IDE and let us see how to implement this tutorial in the hibernate framework!

2. Hibernate Projections Tutorial

Here is a systematic guide for implementing this tutorial in the hibernate framework.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8, MySQL database and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let us review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Hibernate Projections - Application Project Structure
Fig. 2: Application Project Structure

2.3 Project Creation

This section will demonstrate how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Hibernate Projections - Create a Maven Project
Fig. 3: Create a Maven Project

In the New Maven Project window, it will ask you to select the project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ checkbox and just click on the next button to proceed.

Hibernate Projections - Project Details
Fig. 4: Project Details

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Hibernate Projections - Archetype Parameters
Fig. 5: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.hibernate</groupId>
	<artifactId>HibernateProjections</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>Projections in Hibernate</name>
	<packaging>jar</packaging>
</project>

We can start adding the dependencies that developers want like Hibernate, MySQL etc. Let us start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Database and Table Creation

The following script creates a database called projectionsdb with a table: employee. Open MySQL terminal and execute the script.

CREATE DATABASE IF NOT EXISTS projectionsdb;

USE projectionsdb;

CREATE TABLE employee (
	id INT(50) NOT NULL AUTO_INCREMENT, 
	name VARCHAR(200) DEFAULT NULL, 
	designation VARCHAR(200) DEFAULT NULL,
	department VARCHAR(200) DEFAULT NULL,
	PRIMARY KEY (id)
);

INSERT INTO employee (id, name, designation, department) VALUES (1, 'Mike', 'Software Developer', 'Software Development');
INSERT INTO employee (id, name, designation, department) VALUES (2, 'David', 'Team Lead', 'Software Development');
INSERT INTO employee (id, name, designation, department) VALUES (3, 'Peter', 'Manager', 'Human Resources');
INSERT INTO employee (id, name, designation, department) VALUES (4, 'Andrew', 'VP', 'Human Resources');
INSERT INTO employee (id, name, designation, department) VALUES (5, 'Jane', 'VP', 'Software Development');
INSERT INTO employee (id, name, designation, department) VALUES (6, 'Ariana', 'Software Developer', 'Software Development');
INSERT INTO employee (id, name, designation, department) VALUES (7, 'Elsa', 'Manager', 'Administation');

If everything goes well, the table will be created.

Hibernate Projections - Database and Table Creation
Fig. 6: Database and Table Creation

3.2 Maven Dependencies

Here, we specify the dependencies for the Hibernate framework and the MySQL connector. Maven will automatically resolve the rest dependencies such as Hibernate Core, MySQL etc. The updated file will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
	<groupId>com.hibernate</groupId>
	<artifactId>HibernateProjections</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>Projections in Hibernate</name>
	<packaging>jar</packaging>
	<dependencies>
		<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>5.3.7.Final</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.13</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>${project.artifactId}</finalName>
	</build>
</project>

3.3 Java Class Creation

Let us write the Java classes involved in this application.

3.3.1 Implementation of Model Class

Add the following code to the model definition to map the attributes with the column names.

Employee.java

package com.hibernate.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity  
@Table(name= "employee")
public class Employee {

	@Id
	@GeneratedValue(strategy= GenerationType.IDENTITY)
	private int id;
	private String name;
	private String designation;
	private String department;

	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getDesignation() {
		return designation;
	}
	public void setDesignation(String designation) {
		this.designation = designation;
	}
	public String getDepartment() {
		return department;
	}
	public void setDepartment(String department) {
		this.department = department;
	}
}

3.3.2 Implementation of Utility Class

Add the following code to the implementation class for testing the Projections in the Hibernate Criteria.

AppMain.java

package com.hibernate.util;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;

import com.hibernate.model.Employee;

public class AppMain {

	@SuppressWarnings({ "deprecation", "unchecked" })
	public static void main(String[] args) {

		// Creating the config instance & passing the hibernate config file.
		Configuration config = new Configuration();
		config.configure("hibernate.cfg.xml");

		// Session object in hibernate to start the db transaction.
		Session s = config.buildSessionFactory().openSession();

		/***** READING ENTITY WITH SINGLE PROJECTION OBJECT. *****/

		System.out.println("\n===== Reading entity with single projection object. =====\n");

		Criteria c1 = s.createCriteria(Employee.class);

		// Single column.
		Projection pro1 = Projections.property("name");

		// Adding the projection object to the criteria object.
		c1.setProjection(pro1);

		List<String> singlecol = c1.list();

		System.out.println(singlecol);

		/***** READING ENTITY WITH MULTIPLE PROJECTION OBJECTS. *****/

		System.out.println("\n===== Reading entity with multiple projection objects. =====\n");

		Criteria c2 = s.createCriteria(Employee.class);

		// Multiple columns.
		Projection pro2 = Projections.property("name"); 
		Projection pro3 = Projections.property("designation"); 
		Projection pro4 = Projections.property("department"); 

		ProjectionList pList = Projections.projectionList(); 
		pList.add(pro2); 
		pList.add(pro3); 
		pList.add(pro4); 

		// Adding the projection list object to the criteria object.
		c2.setProjection(pList);

		List<Object[]> multicol = c2.list();

		// Used lambda expression technique of jdk1.8 to display the result list.
		multicol.forEach((o) -> {
			System.out.println("Name: " + o[0] +", Designation: " + o[1] + ", Department: " + o[2]);
		});

		/***** AGGREGATION USING PROJECTIONS. *****/

		System.out.println("\n===== Aggregation using projections. =====\n");

		Criteria c3 = s.createCriteria(Employee.class);

		// Adding the 'rowCount()' to the criteria object.
		c3.setProjection(Projections.rowCount());

		List<Long> total = c3.list();

		System.out.println("Total records are: " + total);

		/***** GROUPING RECORDS USING PROJECTIONS. *****/

		System.out.println("\n===== Grouping records using projections. =====\n");

		Criteria c4 = s.createCriteria(Employee.class);

		// Adding the 'groupProperty(property_name)' to the criteria object.
		c4.setProjection(Projections.groupProperty("department"));

		List<Employee> results = c4.list();

		System.out.println(results);

		// Closing the session object.
		s.close();
	}
}

3.4 Hibernate Configuration File

In the configuration file, we will include the database and the mapping class details.

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<!-- Database connection settings. -->
		<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/projectionsdb</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password" />

		<!-- Sql dialect. -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

		<!-- Printing the sql queries to the console. -->
		<property name="show_sql">true</property>

		<!-- Validating the database schema. -->
		<property name="hbm2ddl.auto">validate</property>

		<!-- Model class. -->
		<mapping class="com.hibernate.model.Employee" />
	</session-factory>
</hibernate-configuration>

Important points:

  • Here, we instructed Hibernate to connect to a MySQL database named projectionsdb and the mapping class to be loaded
  • We have also instructed the Hibernate framework to use MySQLDialect i.e. Hibernate will optimize the generated SQL statements for MySQL
  • This configuration will be used to create a hibernate SessionFactory object
  • show_sql tag will instruct the hibernate framework to log all the SQL statements on the console

4. Run the Application

To run the Hibernate application, Right-click on the AppMain class -> Run As -> Java Application. Developers can debug the example and see what happens after every step!

Hibernate Projections - Run Application
Fig. 7: Run Application

5. Project Demo

The code shows the following logs as the output of this tutorial.

Nov 09, 2018 6:00:22 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@7646731d] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.

===== Reading entity with single projection object. =====

Nov 09, 2018 6:00:22 PM org.hibernate.internal.SessionImpl createCriteria
WARN: HHH90000022: Hibernate's legacy org.hibernate.Criteria API is deprecated; use the JPA javax.persistence.criteria.CriteriaQuery instead
Hibernate: select this_.name as y0_ from employee this_
[Mike, David, Peter, Andrew, Jane, Ariana, Elsa]

===== Reading entity with multiple projection objects. =====

Nov 09, 2018 6:00:22 PM org.hibernate.internal.SessionImpl createCriteria
WARN: HHH90000022: Hibernate's legacy org.hibernate.Criteria API is deprecated; use the JPA javax.persistence.criteria.CriteriaQuery instead
Hibernate: select this_.name as y0_, this_.designation as y1_, this_.department as y2_ from employee this_
Name: Mike, Designation: Software Developer, Department: Software Development
Name: David, Designation: Team Lead, Department: Software Development
Name: Peter, Designation: Manager, Department: Human Resources
Name: Andrew, Designation: VP, Department: Human Resources
Name: Jane, Designation: VP, Department: Software Development
Name: Ariana, Designation: Software Developer, Department: Software Development
Name: Elsa, Designation: Manager, Department: Administation

===== Aggregation using projections. =====

Nov 09, 2018 6:00:22 PM org.hibernate.internal.SessionImpl createCriteria
WARN: HHH90000022: Hibernate's legacy org.hibernate.Criteria API is deprecated; use the JPA javax.persistence.criteria.CriteriaQuery instead
Hibernate: select count(*) as y0_ from employee this_
Total records are: [7]

===== Grouping records using projections. =====

Nov 09, 2018 6:00:22 PM org.hibernate.internal.SessionImpl createCriteria
WARN: HHH90000022: Hibernate's legacy org.hibernate.Criteria API is deprecated; use the JPA javax.persistence.criteria.CriteriaQuery instead
Hibernate: select this_.department as y0_ from employee this_ group by this_.department
[Administation, Human Resources, Software Development]

That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!

6. Conclusion

This post defines the implementation of the Projections class in the Hibernate Criteria and helps developers understand the basic configuration required to achieve this. Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Eclipse Project

This was an example of Hibernate Projections for beginners.

Download
You can download the full source code of this example here: HibernateProjections

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button