In this tutorial we shall perform basic database Operations (Create, Retrieve, Update, Delete) using XML based mapping using Hibernate .
This tutorial is divided primarily into the following sections:
- Concept Overview
- Sample program
This example assumes basic familiarity with JDBC (Java DataBase Connectivity) API. This is because Hibernate uses underlying JDBC driver to access the database tier.
Before proceeding with the sample program, it is important to understand some basic concepts in Hibernate.
: A Persistent Entity is a POJO (Plain Old Java Object) that is used by Hibernate to perform database operations like create, retrieve, update and delete. e.g. In a database referring to an organization’s human resources,
could be a persistent entity.
: It refers to the various properties used by Hibernate to connect to database and perform object relational mapping. The configuration is usually detailed in a file named
based on the Document Type Definition mentioned at location “http://www.hibernate.org/dtd/hibernate-configuration.dtd”.
The configuration typically contains information about
- Dababase connectivity parameters like JDBC driver class, database connection URL, username, password, connection pool size, etc
- Dialect related information: One of the key strengths of Hibernate is that it designed to be database agnostic. This is achieved by configuring the Dialect for a particular database
- Mapping files: Lists out the mapping for the entities required to participate in ORM related activities performed by Hibernate
- Schema and query related parameters like default schema, batch fetch size, etc.
- Cache related properties: Configure cache related properties like query cache, second level cache, cache region prefix, etc
- Transaction related properties: Configuration can contain database transaction properties like flush before completion, auto-close session, etc
: Uses the
(mentioned above) to create a Session. It is a thread-safe object and hence can be shared across various classes and used to persist various Persistent Entities in the system.
: A Session represents a live connnection to database and is used to perform database operations on persistent entities like create, retrieve, update and delete. Session also defines the scope for logical database transactions.
From a programming perspective,
is one of the most commonly used API classes in Hibernate.
: This class provides facility to build the query criteria programmatically. Criteria allows programmatic creation of conditionals (e.g. equals, less, greater than, etc.). One can also query using logical operations (e.g. and, or and not) using Criteria. Grouping operations (e.g. sum, max, min, etc.) can also be created using Criteria.
A key benefit of using this class is that the programmer need not get involved in SLQ specific details.
: This refers to the map between object and relational representations of the entity. e.g. A class
may be mapped to a table
, the employee’s
may be mapped to a column
and so on.
Hibernate provides two ways of mapping
- Using XML mapping file
- Using Annotation based mapping
In this tutorial, we shall cover XML mapping files.
Source Package Structure
Create the Employee class (see below) that represents the entity on which basic database operations like insert, select, update and delete shall be performed.
Create the member named id, name, age and salary and create the corresponding accessor methods.
Also override the toString() method to print the details of the Employee class (see lines 53-56 below)
Create the XML based mapping file for the Employee class.
- Map the Employee class to the EMPLOYEE table (see line 6 below)
- Map the id member in Employee class to a column named id (see lines 7 to 9 below). This column represents the primary key in the EMPLOYEE table.
- Map the remaining members name, age and salary (see lines 10-12 below). Note that for the members age and salary, no explicit column name is given. In such case, Hibernate automatically uses the name of the member as the column name.
Create the Hibernate Configuration File as shown below. The key elements of this file are:
- Database connection settings (see lines 8-11 below)
- Hibernate dialect for HyperSQL database (see line 15 below)
- Reference to Employee.hbm.xml mapping file (see line 24 below)
Create the configuration file for Log4J which is used to log the output of the sample program.
Create the HibernateUtil class which is utility class to create Hibernate SessionFactory.
The important sections in this class are:
- Load Hibernate configuration file (see lines 14-15 below)
- Build thie session factory using this configuration (see line 21 below)
Create the Client program that performs basic Create, Retrieve, Update and Delete (in short known as Crud operations) on the Employee class.
- Create the execute() method which calls other methods like insertEmployee(), selectEmployees(), getEmployeeCount(), updateEmployee() and deleteEmployee() (see lines 16-34 below)
- Create the insertEmployee() method (see lines 37-46 below). Create a new Employee named Abigale (see line 42 below) and use Session.save() method (see line 43 below) to insert it.
- Create the selectEmployees() method (see lines 48-58 below). Create a Criteria for the Employee class and use Criteria.list() method to fetch all the Employees (see lines 50-52 below)
- Create the getEmployeeCount() method (see lines 60-70 below) to get the total count of employees in the database. Create a Criteria object for Employee class and use Projections.rowCount() method to fetch the total count of the Employees in the database (see lines 62-55 below)
- Create the updateEmployee() method (see lines 72-83 below). First fetch the Employee with id as 1 (see lines 76-78 below) and then update the name of the Employee to Abigale Updated (see line 79 below)
- Create the deleteEmployee() method to remove an Employee from database (see lines 85-96 below). Fetch an Employee with id as 1 and then delete the Employee using Session.delete() method (see lines 89-92 below)
- From the main() method call the execute() method (see lines 98-100 below)
This sample program has been packaged as a jar installer which will copy the source code (along with all necessary dependencies) on your machine and automatically run the program for you as shown in the steps below. To run the sample program, you only need Java Runtime Environment (JRE) 1.5 or above on your machine and nothing else.
- Save .jar on your machine
- Execute/Run the jar using Java Runtime Environment
(Alternatively you can go the folder containing the hibernatebasiccrudusingxml-installer.jar and execute the jar using java -jar hibernatebasiccrudusingxml-installer.jar command)
- You will see a wizard as shown below:
- Enter the location of the directory where you want the program to install and run (say, C:\Temp)
- The installer will copy the program on your machine and automatically execute it. The expected output indicating that the program has run successfully on your machine is shown in the image below:
- It shows the Employee named Abigale inserted successfully. It also shows the count of all Employees in database as 1 which shows that the Employee was inserted successfully
- The output after updating the name of the employee to Abigale Updated is shown. This shows that update operation was successful.
- After deleting the Employee named Abigale, there are not records in the database which shows that deletion was successful.
This demonstrates that the successful exection of basic operations on Employee using XML based mapping.
This source code for this program is downloaded in the folder specified by you (say, C:\Temp) as an eclipse project called hibernatebasiccrudusingxml. All the required libraries have also been downloaded and placed in the same location. You can open this project from Eclipe IDE and directly browse the source code. See below for details of the project structure.