Home » Enterprise Java » hibernate » Hibernate Calling Stored Procedure 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 Calling Stored Procedure Example

Stored Procedures are a set of compiled SQL statements residing in the database. In hibernate; there are three different approaches to call a stored procedure i.e.

  • Query interface – createSQLQuery(. . . .);
  • StoredProcedureQuery interface – createStoredProcedureQuery(. . . .);
  • @NamedNativeQuery annotation

In this tutorial, we will explore how to create a simple stored procedure in the MySQL database and call it using the StoredProcedureQuery interface in 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 Calling Stored Procedure - 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 Download and Install Hibernate

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

1.3 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 Calling Stored Procedure Example

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 Calling Stored Procedure - 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 Calling Stored Procedure - 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 Calling Stored Procedure - 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 Calling Stored Procedure - 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.storedprocedure</groupId>
	<artifactId>HibernateStoredprocedure</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 sampledb with table employee. Open MySQL terminal or workbench to execute this sql script.

CREATE DATABASE IF NOT EXISTS sampledb;

USE sampledb;

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

INSERT INTO employee (eid, ename, edesig, edept, esal) VALUES (1, 'John Lark', 'Lead', 'Technology', 30000);

INSERT INTO employee (eid, ename, edesig, edept, esal) VALUES (2, 'Natalie Atlas', 'Associate', 'Human Resource', 24000);

INSERT INTO employee (eid, ename, edesig, edept, esal) VALUES (3, 'Daniel Brown', 'Associate', 'Technology', 27000);

INSERT INTO employee (eid, ename, edesig, edept, esal) VALUES (4, 'Tom Hunt', 'Manager', 'Technology', 42000);

INSERT INTO employee (eid, ename, edesig, edept, esal) VALUES (5, 'Edward Clark', 'Senior Manager', 'Human Resource', 55000);

INSERT INTO employee (eid, ename, edesig, edept, esal) VALUES (6, 'Jason Bourne', 'Lead', 'Administration', 24000);

SELECT * FROM employee;

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

Hibernate Calling Stored Procedure - Database and Table
Fig. 6: Database and Table

3.2 Stored Procedures Creation

The following script creates three different stored procedures for the table employee. Open MySQL terminal or workbench to execute this sql script.

----- STORED PROCEDURE QUERY #1 -----
DELIMITER $
CREATE PROCEDURE findAllEmployees ()
	BEGIN
		SELECT * FROM employee;
	END $
DELIMITER ;


----- STORED PROCEDURE QUERY #2 -----
DELIMITER $
CREATE PROCEDURE findEmployeeByDepartment (IN emp_department VARCHAR(200))
	BEGIN
		SELECT * FROM employee emp WHERE emp.edept = emp_department;
	END $
DELIMITER ;


----- STORED PROCEDURE QUERY #3 -----
DELIMITER $
CREATE PROCEDURE findEmployeeCountByDesignation (IN emp_designation VARCHAR(200), OUT designation_count INT(50))
	BEGIN
		SELECT COUNT(*) INTO designation_count FROM employee emp WHERE emp.edesig = emp_designation;
	END $
DELIMITER ;

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

Hibernate Calling Stored Procedure - Stored Procedures
Fig. 7: Stored Procedures

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.storedprocedure</groupId>
	<artifactId>HibernateStoredprocedure</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>Hibernate stored procedure example</name>
	<description>A tutorial on calling the stored procedure(s) in the hibernate5 framework</description>
	<packaging>jar</packaging>
	<dependencies>
		<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>5.4.0.CR2</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.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 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;
	}

	@Override
	public String toString() {
		return "Employee [eid=" + eid + ", ename=" + ename + ", edesig=" + edesig + ", edept=" + edept + ", esal="
				+ esal + "]";
	}
}

3.4.2 Implementation of Utility Class

Add the following code to the implementation class for calling the Stored Procedures in the hibernate framework.

AppMain.java

package com.hibernate.util;

import java.util.List;

import javax.persistence.ParameterMode;
import javax.persistence.StoredProcedureQuery;

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

import com.hibernate.model.Employee;

public class AppMain {

	@SuppressWarnings("unchecked")
	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 stored procedure queries.

		// Stored procedure query #1
		System.out.println(":::: Find all employees ::::");

		StoredProcedureQuery allemployees = s.createStoredProcedureQuery("findAllEmployees", Employee.class);

		List elist = (List) allemployees.getResultList();

		for(Employee employee : elist) {
			System.out.println(employee.toString());
		}

		// Stored procedure query #2
		System.out.println("\n:::: Find employees department wise ::::");

		StoredProcedureQuery department = s.createStoredProcedureQuery("findEmployeeByDepartment", Employee.class);
		department.registerStoredProcedureParameter("emp_department", String.class, ParameterMode.IN);

		String dparam = "Technology";
		department.setParameter("emp_department", dparam);

		List dlist = (List) department.getResultList();

		for(Employee employee : dlist) {
			System.out.println(employee.toString());
		}

		// Stored procedure query #3
		System.out.println("\n:::: Find employee count by designation ::::");

		StoredProcedureQuery count = s.createStoredProcedureQuery("findEmployeeCountByDesignation");
		count.registerStoredProcedureParameter("emp_designation", String.class, ParameterMode.IN);
		count.registerStoredProcedureParameter("designation_count", Integer.class, ParameterMode.OUT);

		String param = "Lead";
		count.setParameter("emp_designation", param);
		count.execute();

		Integer employee_count = (Integer) count.getOutputParameterValue("designation_count");
		System.out.println("Employee count for designation= " + param + " is= " + employee_count);

		// 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/sampledb</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 sampledb 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 Calling Stored Procedure - Run Application
Fig. 8: Run Application

5. Project Demo

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

Dec 12, 2018 10:35:55 AM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@46044faa] 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.
Dec 12, 2018 10:35:55 AM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]

// STORED PROCEDURE QUERY #1

:::: Find all employees ::::
Hibernate: {call findAllEmployees()}
Employee [eid=1, ename=John Lark, edesig=Lead, edept=Technology, esal=30000]
Employee [eid=2, ename=Natalie Atlas, edesig=Associate, edept=Human Resource, esal=24000]
Employee [eid=3, ename=Daniel Brown, edesig=Associate, edept=Technology, esal=27000]
Employee [eid=4, ename=Tom Hunt, edesig=Manager, edept=Technology, esal=42000]
Employee [eid=5, ename=Edward Clark, edesig=Senior Manager, edept=Human Resource, esal=55000]
Employee [eid=6, ename=Jason Bourne, edesig=Lead, edept=Administration, esal=24000]

// STORED PROCEDURE QUERY #2

:::: Find employees department wise ::::
Hibernate: {call findEmployeeByDepartment(?)}
Employee [eid=1, ename=John Lark, edesig=Lead, edept=Technology, esal=30000]
Employee [eid=3, ename=Daniel Brown, edesig=Associate, edept=Technology, esal=27000]
Employee [eid=4, ename=Tom Hunt, edesig=Manager, edept=Technology, esal=42000]

// STORED PROCEDURE QUERY #3

:::: Find employee count by designation ::::
Hibernate: {call findEmployeeCountByDesignation(?,?)}
Employee count for designation= Lead is= 2

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 calling the stored procedures 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 calling the Stored Procedures in the Hibernate framework for beginners.

Download
You can download the full source code of this example here: HibernateStoredprocedure
(+1 rating, 1 votes)
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