Hibernate CRUD App
By ski11up.com
Hibernate ORM is developed by Red Hat and an open-source framework that provides the mapping between Java Object and Relational Database.
Hibernate uses Hibernate Query Language for performance DB operations.
The below diagram depicts how to, hibernate works as a layer between the application layer and the relational database.

Design
We will create a table as contacts
having fields as id
, first_name
, last_name
and email
which will map to Java Object
Contact
having attributes as id
, firstName
, lastName
and email
.

Project Setup
Maven
project with the following dependencies.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
And a hibernate.cfg.xml
under src/main/resources
.
<!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>
<!-- Hibernate Dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- JDBC Database connection settings -->
<property name="connection.driver_class">
com.mysql.cj.jdbc.Driver</property> (1)
<property name="connection.url">
jdbc:mysql://localhost:3306/sales</property> (2)
<property name="connection.username">ski11up</property> (3)
<property name="connection.password">dbadmin</property> (4)
<!-- Connection Pool Settings -->
<property name="connection.pool_size">1</property>
<property name="show_sql">true</property>
<property name="current_session_context_class">thread</property>
<property name="hibernate.generate_statistics">false</property>
</session-factory>
</hibernate-configuration>
1 | driver used for connecting with the database |
2 | db location |
3 | user name of the schem |
4 | user password of the schema |
That’s it.
Database
Let’s create a DB user, schema
and contacts
table.
I am using MySql
you can use any RDBMS
but make sure that equivalent maven
dependency will be imported.
Use below SQL to create a user, which will perform operations on the new schema.
CREATE USER 'ski11up'@'localhost' IDENTIFIED BY 'dbadmin';
GRANT ALL PRIVILEGES ON * . * TO 'ski11up'@'localhost';
ALTER USER 'ski11up'@'localhost' IDENTIFIED WITH mysql_native_password BY 'dbadmin';
Create a table with the below details.
CREATE DATABASE IF NOT EXISTS `sales`;
USE `sales`;
--
-- Table structure for table `contacts`
--
DROP TABLE IF EXISTS `contacts`;
CREATE TABLE `contacts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(45) DEFAULT NULL,
`last_name` varchar(45) DEFAULT NULL,
`email` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
Always use schema specific user |
We have completed the RDBMS
setup.
Application
We need to create a Java
Object
which will be mapped to the equivalent table in the database.
@Entity (1)
@Table(name = "contacts", (2)
schema = "sales", (3)
uniqueConstraints= {@UniqueConstraint(columnNames={"id"})}) (4)
public class Contact {
@Id (5)
@GeneratedValue(strategy = GenerationType.IDENTITY) (6)
@Column(name = "id", nullable = false, unique = true) (7)
private int id;
@Column(name = "first_name", nullable = false)
private String firstName;
@Column(name = "last_name", nullable = false)
private String lastName;
@Column(name = "email", nullable = false)
private String email;
...
}
1 | class needs to be specified as an Entity, it can be excluded if we have the exact match between the Java Class and the SQL Table |
2 | name of the table to which we are mapping the class |
3 | name of the schema |
4 | states that it has a primary key on the id column |
5 | same as above, way to specify the column as primary key |
6 | generating the unique id for each record |
7 | name of the column to which we are mapping the object attribute |
Above is a code snippet that just shows important things that does require to mention, check the full source code in the git
repo.
Lets work on the main app.
We will create 3 records in the database for each of the Create
, Delete
, Update
operation. Once the application code is executed we expect the last record will be deleted and the 1st and 2nd record will be updated.
public static void main(String[] args) {
Contact contact = new Contact(
"Jagdeep",
"Jain",
"jagdeep@ski11up.com"); (1)
Contact contactUpdate = new Contact(
"Sandeep",
"Jain",
"jagdeep@ski11up.com");
Contact contactDelete = new Contact(
"Pradeep",
"Jain",
"pradeep@ski11up.com");
Configuration cfg = new Configuration().configure(); (2)
StandardServiceRegistry sr =
new StandardServiceRegistryBuilder()
.applySettings(cfg.getProperties())
.build(); (3)
Metadata m =
new MetadataSources(sr)
.addAnnotatedClass(Contact.class)
.getMetadataBuilder().build(); (4)
SessionFactory sf = m.getSessionFactoryBuilder().build(); (5)
Session session = sf.openSession(); (6)
try {
// Create
session.getTransaction().begin(); (7)
session.save(contact); (8)
session.getTransaction().commit(); (9)
// Read - Query is on the Contact Object but not on the DB Table
session.getTransaction().begin(); (10)
List<Contact> contactList =
session.createQuery("FROM Contact").list(); (11)
contactList.forEach(
contactDetails -> {
System.out.println( "Contact # " + contactDetails);
}
);
// Update based on HQL
session.getTransaction().begin();
session.save(contactUpdate);
session.getTransaction().commit();
session.getTransaction().begin();
session.createQuery(
"UPDATE Contact " +
"set email='sandeep@ski11up.com' " +
"WHERE firstName='Sandeep'")
.executeUpdate(); (12)
session.getTransaction().commit();
// Delete based on HQL
session.getTransaction().begin();
session.save(contactDelete);
session.getTransaction().commit();
session.getTransaction().begin();
Contact contactToDelete =
session.get(Contact.class, contactDelete.getId()); (13)
session.delete(contactToDelete); (14)
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
}
finally {
session.close();
sf.close();
}
}
1 | creating objects which we want to insert into the table |
2 | if the file is in src/main/resources and has the name hibernate.cfg.xml then there is no need to specify the name of a configuration file |
3 | get the handle of the configuration file |
4 | get the handle of the contact object |
5 | get the session factory handle |
6 | get the actual session we need to use for doing CRUD operations |
7 | starting the transaction |
8 | create statement on the object |
9 | committing the transaction |
10 | once again begin the transaction as the previous transaction is completed |
11 | select statement on the object |
12 | update statement on the object |
13 | we need to get the object to perform operations, here we are getting the id of the record where the first name is Pradeep, check the created object in starting of the main method |
14 | executing delete statement on the object which will perform operations in the database |
Execution
Open the CRUDApp.java
and execute as Java App
.
Check the contacts
table for the updates made by the code.

If you run this code again, you will see that record 3
will be skipped and the next id
value will be 4
, this is because we have deleted record number 3
.
Source Code
You can either git fork
, git clone
or download this repository hibernate-demo.