Hibernate doWork() method Example

In this tutorial, we will learn Hibernate 4 Work interface and Session.doWork() 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 doWork - 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.doWork() 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 doWork() 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 doWork - 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 doWork - 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 doWork - 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 doWork - 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:


<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">
	<name>Hibernate stored procedure example</name>

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.


USE ducat;

CREATE TABLE employee (
	esal INT(100) DEFAULT NULL,

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

Hibernate doWork - Table Creation
Fig. 6: Table Creation

3.2 Stored Procedure Creation

The following script creates a stored procedure to insert the records in the employee table.

CREATE PROCEDURE addEmployee (IN name VARCHAR(50), IN designation VARCHAR(100), IN department VARCHAR(100), IN salary INT)
		INSERT INTO employee(ename, edesig, edept, esal) VALUES(name, designation, department, salary);
	END $

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

Hibernate doWork - 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:


<project xmlns="http://maven.apache.org/POM/4.0.0"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

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

		<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
		<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->

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.


package com.hibernate.model;

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

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

	@GeneratedValue(strategy= GenerationType.IDENTITY)
	private int eid;
	private String ename;
	private String edesig;
	private String edept;
	private int esal;

	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 getEdesig() {
		return edesig;
	public void setEdesig(String edesig) {
		this.edesig = edesig;
	public String getEdept() {
		return edept;
	public void setEdept(String edept) {
		this.edept = edept;
	public int getEsal() {
		return esal;
	public void setEsal(int esal) {
		this.esal = esal;

3.4.2 Implementation of Utility Class

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


package com.hibernate.util;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Random;

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

public class AppMain {

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

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

		// Opening the transaction.

		// Inserting the data to the database using the Hibernate's Work interface.
		// Hibernate's doWork() method performs the CRUD operations in the database!
		s.doWork(new Work(){
			public void execute(Connection conn) throws SQLException {
				int count = 0;
				CallableStatement stmt = null;
				try {
					String sqlstring = "{call addEmployee(?, ?, ?, ?)}";
					stmt = conn.prepareCall(sqlstring);

					for(int i=1, j=100; i<6; i++, j=j+10) {
						// The key parameters must match the input argument names of the stored procedure.
						stmt.setString("name", "Employee"+i);
						stmt.setString("designation", "Manager"+j);
						stmt.setString("department", "Technology");
						stmt.setInt("salary", new Random().nextInt(100000 - 50000) + 50000);

						count = count + stmt.executeUpdate();
					System.out.println(count + " rows inserted.");
				} finally {

		// Committing the employee data to the database.

		// Closing the session object.

3.5 Hibernate Configuration File

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


<?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">
		<!-- 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" />

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 doWork - Run Application
Fig. 8: Run Application

5. Project Demo

Output like below will be displayed in the database.

Hibernate doWork - Records Inserted
Fig. 9: Records Inserted in the Db

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.doWork() 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.doWork() method in the Hibernate framework.

You can download the full source code of this example here: Hibernate doWork() method Example


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).
Notify of

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

Newest Most Voted
Inline Feedbacks
View all comments
4 years ago

Are Stored Procedures a Good Practice?

Back to top button