Home » Enterprise Java » hibernate » Hibernate doReturningWork() method Example

About Yatin

Yatin
The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.

Hibernate doReturningWork() method Example

In this tutorial, we will learn Hibernate 4 Returning Work interface and Session.doReturningWork() method for Jdbc.

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 the 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 doReturningWork - Hibernate Overview
Fig. 1: Hibernate Overview

1.1 Annotations in Hibernate

  • 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 Work interface in Hibernate 4

In the hibernate framework; developers can easily convert the Session object to Jdbc connection object. Thus, hibernate 4 introduces two new methods in the session interface i.e.

  • Session.doWork(): For performing the CRUD operations
  • Session.doReturningWork(): For returning the data from the database

To understand the above concept, let us open the eclipse ide and implement the Session.doReturningWork() method in the hibernate framework! Do note, we are assuming while practicing this code you already have Hibernate and MySql installed on your systems.

2. Hibernate doReturningWork() method Example

Here is a systematic guide for implementing this tutorial.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8, MySQL database and Maven.

2.2 Project Structure

In case you are confused about where you should create the corresponding files or folder, let us review the project structure of the application.

Hibernate doReturningWork - 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 doReturningWork - 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 doReturningWork - 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 doReturningWork - 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>Hibernatedoreturningworkmethodtutorial</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>Hibernate stored procedure example</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 ducat with the table employee. Open MySQL terminal or workbench to execute this sql script.

CREATE DATABASE IF NOT EXISTS ducat;

USE ducat;

CREATE TABLE employee (
	eid INT(50) NOT NULL AUTO_INCREMENT, 
	ename VARCHAR(200) DEFAULT NULL, 
	ecompany VARCHAR(200) DEFAULT NULL,
	edept VARCHAR(100) DEFAULT NULL,
	egender VARCHAR(100) DEFAULT NULL,
	PRIMARY KEY (eid)
);

insert into employee (eid, ename, ecompany, edept, egender) values (1, 'Jolene Gredden', 'Centizu', 'Research and Development', 'Female');
insert into employee (eid, ename, ecompany, edept, egender) values (2, 'Virgie Madle', 'Tambee', 'Legal', 'Male');
insert into employee (eid, ename, ecompany, edept, egender) values (3, 'Vaughn Sager', 'Jabbercube', 'Product Management', 'Male');
insert into employee (eid, ename, ecompany, edept, egender) values (4, 'Jordan Casajuana', 'Jetwire', 'Services', 'Female');
insert into employee (eid, ename, ecompany, edept, egender) values (5, 'Demetre Rubury', 'Dabfeed', 'Marketing', 'Male');
insert into employee (eid, ename, ecompany, edept, egender) values (6, 'Selinda Hasser', 'Trudeo', 'Accounting', 'Female');
insert into employee (eid, ename, ecompany, edept, egender) values (7, 'Kerwin Michelin', 'Kayveo', 'Research and Development', 'Male');
insert into employee (eid, ename, ecompany, edept, egender) values (8, 'Jarrod Godon', 'Wikibox', 'Training', 'Male');
insert into employee (eid, ename, ecompany, edept, egender) values (9, 'Ernst Goodlip', 'Skyble', 'Services', 'Male');
insert into employee (eid, ename, ecompany, edept, egender) values (10, 'Buddy Messager', 'Skynoodle', 'Business Development', 'Male');

If everything goes well, the table will be created and displayed.

Hibernate doReturningWork - Table Creation
Fig. 6: Table Creation

3.2 Stored Procedure Creation

The following script creates a stored procedure to fetch the records from the
employee table.

----- STORED PROCEDURE QUERY TO RETURN THE EMPLOYEE LIST FROM THE DATABASE.
DELIMITER $
CREATE PROCEDURE returnEmployeeList()
	BEGIN
		SELECT * FROM employee;
	END $
DELIMITER ;

If everything goes well, the stored procedure will be created as shown in Fig. 7.

Hibernate doReturningWork - Stored Procedure
Fig. 7: Stored Procedure

3.3 Maven Dependencies

Here, we specify the dependencies for the Hibernate framework and the MySQL connector. Maven will automatically resolve the rest dependencies such as Persistence, 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>Hibernatedoreturningworkmethodtutorial</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<name>Hibernate doReturningWork() method tutorial</name>
	<description>A tutorial to understand the doReturningWork() method in the hibernate framework</description>

	<dependencies>
		<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>5.4.1.Final</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.15</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>${project.artifactId}</finalName>
	</build>
</project>

3.4 Java Class Creation

Let us write the Java classes involved in this application.

3.4.1 Implementation of Model Class

This class maps the model attributes with the table column names. 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 eid;
	private String ename;
	private String ecompany;
	private String edept;
	private String egender;

	public Employee(int eid, String ename, String ecompany, String edept, String egender) {
		this.eid = eid;
		this.ename = ename;
		this.ecompany = ecompany;
		this.edept = edept;
		this.egender = egender;
	}
	public int getEid() {
		return eid;
	}
	public void setEid(int eid) {
		this.eid = eid;
	}
	public String getEname() {
		return ename;
	}
	public void setEname(String ename) {
		this.ename = ename;
	}
	public String getEcompany() {
		return ecompany;
	}
	public void setEcompany(String ecompany) {
		this.ecompany = ecompany;
	}
	public String getEdept() {
		return edept;
	}
	public void setEdept(String edept) {
		this.edept = edept;
	}
	public String getEgender() {
		return egender;
	}
	public void setEgender(String egender) {
		this.egender = egender;
	}
	@Override
	public String toString() {
		return "Employee [Id=" + eid + ", Name=" + ename + ", Company=" + ecompany + ", Department=" + edept
				+ ", Gender=" + egender + "]";
	}
}

3.4.2 Implementation of Utility Class

Add the following code to the implementation class for using the doReturningWork() method in the hibernate framework.

AppMain.java

package com.hibernate.util;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.jdbc.ReturningWork;

import com.hibernate.model.Employee;

public class AppMain {

	public static void main(String[] args) {		
		// Creating the configuration instance & passing the hibernate configuration file.
		Configuration config = new Configuration();
		config.configure("hibernate.cfg.xml");

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

		// Fetching the data from the database using the Hibernate's ReturningWork interface.
		// Hibernate's doReturningWork() method performs the SELECT operations in the database!
		List<Employee> emp = null;

		// Just pass object to ReturningWork<T> interface.
		emp = s.doReturningWork(new ReturningWork<List<Employee>>() {
			@Override
			public List<Employee> execute(Connection connection) throws SQLException {

				Employee e = null;
				CallableStatement cstmt= null;
				List<Employee> inrList = new ArrayList<Employee>();
				try {
					String sqlString= "{call returnEmployeeList}";
					cstmt = connection.prepareCall(sqlString);

					ResultSet rs = cstmt.executeQuery();
					while(rs.next()) {
						e = new Employee(rs.getInt("eid"), rs.getString("ename"), rs.getString("ecompany"), rs.getString("edept"), rs.getString("egender"));
						inrList.add(e);
					}
				} finally {
					cstmt.close();
				}
				return inrList;
			}
		});

		// Displaying the employee records returned from the database table.
		if(emp != null && emp.size() > 0) {
			for(Employee e : emp) {
				System.out.println(e.toString());
			}
		} else {
			System.out.println("No employee record exists in the table.");
		}

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

3.5 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/ducat</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password" />
		
		<!-- Sql dialect -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
		
		<!-- Printing the sql queries to the console -->
		<property name="show_sql">true</property>
		
		<!-- Mapping to the create schema DDL -->
		<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 ducat and the mapping class to be loaded
  • We have also instructed the Hibernate framework to use MySQL5Dialect i.e. Hibernate will optimize the generated SQL statements for MySQL
  • This configuration will be used to create a hibernate SessionFactory object
  • hbm2ddl.auto tag will instruct the hibernate framework to validate the database table schema at the application startup
  • 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 doReturningWork - Run Application
Fig. 8: Run Application

5. Project Demo

Output like below will be displayed in the console.

INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]

Employee [Id=1, Name=Jolene Gredden, Company=Centizu, Department=Research and Development, Gender=Female]
Employee [Id=2, Name=Virgie Madle, Company=Tambee, Department=Legal, Gender=Male]
Employee [Id=3, Name=Vaughn Sager, Company=Jabbercube, Department=Product Management, Gender=Male]
Employee [Id=4, Name=Jordan Casajuana, Company=Jetwire, Department=Services, Gender=Female]
Employee [Id=5, Name=Demetre Rubury, Company=Dabfeed, Department=Marketing, Gender=Male]
Employee [Id=6, Name=Selinda Hasser, Company=Trudeo, Department=Accounting, Gender=Female]
Employee [Id=7, Name=Kerwin Michelin, Company=Kayveo, Department=Research and Development, Gender=Male]
Employee [Id=8, Name=Jarrod Godon, Company=Wikibox, Department=Training, Gender=Male]
Employee [Id=9, Name=Ernst Goodlip, Company=Skyble, Department=Services, Gender=Male]
Employee [Id=10, Name=Buddy Messager, Company=Skynoodle, Department=Business Development, Gender=Male]

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 Session.doReturningWork() method in the hibernate framework 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 using the Session.doReturningWork() method in the Hibernate framework.

Download
You can download the full source code of this example here: Hibernate doReturningWork() method Example
(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of