In this tutorial we shall perform basic database Operations (Create, Retrieve, Update, Delete) using JPA Annotations 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.
It also assumes familiarity with Java Annotations which are used to specify metadata information for Java elements.
Before proceeding with the sample program, it is important to understand some basic concepts in Hibernate.
Java Persistence API (JPA)
: An API standard for object relational mapping. The benefit of using JPA is that underlying persistence JPA compliant technologies can be modified comparatively easily (e.g. It would be comparatively easier to migrate from EclipseLink ORM to Hiberate ORM as they are both JPA compliant)
: 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 (see this tutorial for XML based mapping file)
- Using JPA Annotation based mapping
In this tutorial, we shall cover JPA annotations based mapping.
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)
The key points regarding JPA Annotation based mapping is detailed out below:
- The class Employee is annotation using @Entity (see line 9 below). This marks this class as a persistent entity on which database operations shall be performed.
- Map the Employee class to the EMPLOYEE table using @Table annotation (see line 10 below)
- Map the member id to the column ID (see line 14 below) using @Column annotation. This member is defined as a primary key using the @Id annotation
- Map the other members like name, age and salary using @Column annotation (see lines 17-23 below). Note that when the name attribute of the @Column annotation is not given as in the case of age and salary members (see lines 20-23 below) then the automatically the name of the member is assigned as the corresponding 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 JPA annotated Employee class (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 database operations like insert, select, update and delete 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-62 below). Create a Criteria for the Employee class and use Criteria.list() method to fetch all the Employees (see lines 52-59 below)
- Create the getEmployeeCount() method (see lines 64-74 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 68-71 below)
- Create the updateEmployee() method (see lines 78-89 below). First fetch the Employee with id as 1 (see lines 82-84 below) and then update the name of the Employee to Abigale Updated (see line 85 below)
- Create the deleteEmployee() method to remove the Employee from database (see lines 91-102 below). Fetch an Employee with id as 1 and then delete the Employee using Session.delete() method (see lines 95-98 below)
- From the main() method call the execute() method (see lines 104-106 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 hibernatebasicoperationsusingannotations-installer.jar on your machine
- Execute/Run the jar using Java Runtime Environment
(Alternatively you can go the folder containing the hibernatebasicoperationsusingannotations-installer.jar and execute the jar using java -jar hibernatebasicoperationsusingannotations-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 hibernatebasiccrudoperations. 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.
1 thought on “Hibernate: Performing Basic Database Operations (select, insert, update, delete) Using JPA Annotation Based Mapping”
Hibernate should not be used with a session-per-operation, but with one session as a unit of work, in which everything on persistent objects/ entities is done, and Hibernate decides when to make database access (write operations, CUD, usually with the final commit()). It’s Persistence Ignorance, not mapping objects to individual SQL statements. Attempting to use Hibernate for a series of single CRUD operations is wrong.
The above code may be good for simple examples, but there should not be a repository or other data access layer, with insert/update/delete(Entity) methods, creating and closing a micro-session internally.