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
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 operationsSession.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.
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
.
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.
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
.
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>Hibernatedoworkmethodtutorial</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, edesig VARCHAR(200) DEFAULT NULL, edept VARCHAR(100) DEFAULT NULL, esal INT(100) DEFAULT NULL, PRIMARY KEY (eid) );
If everything goes well, the table will be created and displayed.
3.2 Stored Procedure Creation
The following script creates a stored procedure to insert the records in the employee
table.
----- STORED PROCEDURE QUERY TO INSERT THE RECORDS IN THE DATABASE. ----- DELIMITER $ CREATE PROCEDURE addEmployee (IN name VARCHAR(50), IN designation VARCHAR(100), IN department VARCHAR(100), IN salary INT) BEGIN INSERT INTO employee(ename, edesig, edept, esal) VALUES(name, designation, department, salary); END $ DELIMITER ;
If everything goes well, the stored procedure will be created as shown in Fig. 7.
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>Hibernatedoworkmethodtutorial</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>Hibernate doWork() method tutorial</name> <description>A tutorial to understand the doWork() 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 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.
AppMain.java
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(); config.configure("hibernate.cfg.xml"); // Hibernate session object to start the db transaction. Session s = config.buildSessionFactory().openSession(); // Opening the transaction. s.beginTransaction(); // 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(){ @Override 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 { stmt.close(); } } }); // Committing the employee data to the database. s.getTransaction().commit(); // 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 startupshow_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!
5. Project Demo
Output like below will be displayed in the database.
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
Are Stored Procedures a Good Practice?
Stored procedures are great for speeding up some database operations. My idea of using stored procedures is in a targeted manner to improve performance where benchmarking is required. Moreover, they offer code reuse, security, protection from SQL injection, and encapsulation.