Hibernate Development Process :CRUD

To Do List

  1. Add Hibernate Configuration file
  2. Annotate Java Class
  3. Develop Java Code to perform database operations
Configuration File 
Hibernate 
JOBC URL 
user id 
JDBC

Hibernate uses JDBC in the background for communicating with the database

So the bulk of the information we will have in our config file is actually JDBC configuration (url, userid, password and so on … ), just to tell hibernate how to connect to the database.

In our Java project within src directory (root of the src directory/ actual class path of our application ) we will create a hibernate.cfg.xml file, which will contain below code:

Step 1: Add hibernate configuration file

=========================(hibernate.cfg.xml)=====================================

<!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>

        <!– JDBC Database connection settings –>

        <property name=”connection.driver_class”>com.mysql.cj.jdbc.Driver</property>

        <property name=”connection.url”>jdbc:mysql://localhost:3306/dbname?useSSL=false&amp;serverTimezone=UTC</property>

        <property name=”connection.username”>username</property>

        <property name=”connection.password”>password</property>

        <!– JDBC connection pool settings … using built-in test pool –>

        <property name=”connection.pool_size”>1</property>

        <!– Select our SQL dialect –>

        <property name=”dialect”>org.hibernate.dialect.MySQLDialect</property>

        <!– Echo the SQL to stdout –>

        <property name=”show_sql”>true</property>

<!– Set the current session context –>

<property name=”current_session_context_class”>thread</property>

    </session-factory>

</hibernate-configuration>

=======================================================================

Step 2: Annotate Java Class

Terminology

Entity Class : Java class that is mapped to a database table.

Its plain old java class (POJO) with fields and getters and setters methods and we simply add annotations on it to help with mapping it to a database table

We somehow need to tell Hibernate how to map this class to the actual table and also map fields to the actual columns

()bjeet-to-Relational Mapping ()RM 
Java Class 
- id:int 
• fvstName : String 
- lastName String 
- email String 
Hibernate 
Database Table 
d INT 
VARCHAR(4S) 
ast_narne VARCHAR(45) 
entail vARCHAR(45)

Two option for Mapping a class:

  1. XML config file (legacy approach)
  2. Java Annotations (modern, preferred)
    1. Map class to database table
    2. Map fields to database columns
Step l: Map class to database table 
@Entity 
" Student " ) 
public class 
Student { 
Java Class 
int 
• firstNarne : String 
• : Str"tg 
• email String 
Database Table 
o VARCHAR(45) 
O ast_næ-ne VARCHAR(4S) 
—nail VARCHAR(45)
  • @Id is the primary key
  • Field name may differ from the database name and in case if we have defined the @Column name then it must be same as the name of a column in the table.
  • Also if the field names and the column names are the same there is no need to specify the @Column annotation/attribute as hibernate will automatically pick that up.
Step 2: Map fields to database columns 
@Entity 
public class Student { 
private int id; 
private String firstName; 
Java Class 
• hrstName : String 
- String 
- : String 
Database Table 
o VARCHAR(45) 
O VARCHAR(4S) 
O —nail VARCHAR(45)

Step 3:

Map class to database table

Use below imports as these imports are from java persistence api, it is a standard interface that hibernate implements:

import javax.persistence.Entity;

import javax.persistence.Table;

FAQ: Why we are using JPA Annotation instead of Hibernate ?

QUESTION:

Why we are using JPA Annotation instead of Hibernate ?

For example, why we are not using this org.hibernate.annotations.Entity?

ANSWER:

JPA is a standard specification. Hibernate is an implementation of the JPA specification.

Hibernate implements all of the JPA annotations.

The Hibernate team recommends the use of JPA annotations as a best practice.

Hibernate CRUD Features

Two Key Players 
Class 
SessionFactory 
Session 
Description 
Reads the hibemate config file 
Creates Session objects 
Heavy-weight object 
Only create once in your app 
Wraps a JDBC connection 
Main Object used to save/retrieve objects 
Short-lived object 
Retrieved from SessionFactory

Create Object

CreateStudent.java x 
9 public class CreateStudent 
Ile 
public static void main (String[] args) { 
// create session factory 
SessionFactot"y factory = new 
. buildSessionFactoy(); 
// create session 
Session session = factory.getCurrentSession(); 
try 
// create student object 
System new object.. 
Student 
student = new ' 
// start a transmission 
session . begin Transaction ; 
// save the student object 
session . saveOrUpdate(student) ; 
// commit transaction 
session . getTransaction . commit() ; 
"sasukekavtiyal@gmail.com"); 
System has been saved successfully"); 
catch (Exception 
error occured. Cannot save the object ! ! 
e. printStackTrace(); 
finally 
System the factory connection"); 
factory. close() ;

Data inside MySql table

first name 
Adarsh 
last name 
email 
adarshkavtyaICgmaiI com 
sachinkavtyaICgmaiI com 
sasukekavtyaICgmaiI com

Note: Generally database generate a primary key (auto incremental ). Now if you wanna be explicit you can tell hibernate how to actually perform generation using given strategy to generate that id.

If we don’t specify anything by default it will use the appropriate strategy for that given database implementation.

@GeneratedValue is a hibernate annotation

I libernate Identity - Primary Kev 
@Entity 
public class Student { 
Let MySOL handle the 
generation 
AUTO_INCREMENT 
IDENTITY) 
private int id;

Some other type of ID generation Strategies

GenerationType. AUTO 
GenerationType. IDENTITY 
Generationrype. SEQUENCE 
GenerationType. TABL E 
Description 
Pick an appropriate strategy for the particular 
primary keys using database identity 
primary keys using a database sequence 
primary keys using an underlying 
base table to ensure uniqueness

Most commonly used for MySql is AUTO_INCREMENT which is GenerationType.IDENTITY. That’s a good one because it allows you to leverage the auto increment feature of mysql.

You can also define your own CUSTOM generation strategy.

Create implementation of org.hibernate.id.IdentifierGenerator.

Override the method: public serializable generator( add your custom business logic of incrementing primary key in a sequence ).

Retrieving a Java Object with Hibernate

RetriveStudent.java x 
Ile 
public static void main (String 
args) { 
int 
// create session factory 
SessionFactot"y factory = new 
Session session = factory.getCurrentSession(); 
try 
// start a transmission 
session . begin Transaction ; 
// retrieve student object using primary key 
Student 
dbStudent = session.get(Student.cIass, id) 
(dbStudent null) { 
System has been retrieved succesfully" • 
System.out. " 
+ dbStudent); 
else 
System.out. with id: " 
session . getTransaction . commit() ; 
catch (Exception 
+ id + 
' not found"); 
System error occured. Cannot retieve object ! ! 
finally 
System the factory connection"); 
factory. close() ;
Console X 
'-terminated> RetriveStudent [Java Application] FilesUava\idkI 18.0 261 Ibin\iavaw.exe (Nov 15, 2020, PM — 12:z 
Nov 15, 2Ø2Ø 
INFO: HHHIØØØIØØI: Connection properties: {user=hdstudent, 
Nov 15, 2Ø2Ø 
INFO: HHHIØØØIØØ3: Autocommit mode: false 
Nov 15, 2Ø2Ø 
INFO: HHHØØØ115: Hibernate connection pool size: I (min—I) 
Nov 15, 2Ø2Ø org.hidernste.dislect.oislect 
:NFO: HHHØØØ4ØØ: Using dialect: org.hide .VI%SQLDisIect 
Hibernate: select studentø . id as idl studentø . email as emai12 
Object has been retrieved succesfully 
dbStudent: Student Cid=3, firstName=Itachi, lastName=KvT, 
Closing the factory connection 
15, 2Ø2Ø 12:49 
studentø 
. first name a:

Query on objects using hibernate

Hibernate Query Language (HQL)

  • Query language for retrieving objects
  • Similar in nature to SQL
    • Where, like, order by, join, in, etc …

Retrieve all Students

  • List<Student> studentList = session.createQuery(“from <table_name>”).getResultList();

Retrieving Students: lastName  = ‘Kavtiyal’

  • List<Student> studentList = session.createQuery(“from Student s where s.lastName=’kavtiyal'”).getResultList();

Retrieving Students using OR predicate

  • List<Student> studentList = session.createQuery(“from Student s where s.lastName=’kavtiyal’ OR s.firstName=’Adarsh'”).getResultList();

Retrieving Students using LIKE predicate

  • List<Student> studentList = session.createQuery(“from Student s where s.email LIKE ‘adarshkavtiyal@gmail.coml’ “).getResultList();

“student”: tableName

“s”: alias

“.lastName”: java object property name

QueryStudent.java x 
SessionFactot"y factory = new 
Session session = factory.getCurrentSession(); 
try 
// start transaction 
session . begin Transaction ; 
// query database using HQL 
studentList 
session. Student") .getResuItList(); 
// Retrieving Students: lastName = 
= session. Student s where s.IastName='kavtiyaI"' 
. getResuItList(); 
// Retrieving Students using OR predicate 
= session 
. Student s where s. lastName= 
' KvT' 
// Retrieving Students using LIKE predicate 
= session 
. Student s where s.email LIKE 
If (etudentLise null 
88 ! isEmpty())) { 
System have been retrived"); 
// display the retrieved objects 
for (Student 
tempStudent : studentLis ) { 
OR s. firstName='Adarsh ) .getResuItList(); 
' adarshkavtiyal@gmail.com 
. getResuItList(); 
Sy stem . out. println (tempStudent) ; 
else 
not found ! ! " ) • 
// commit the transaction
Console X 
QuervStudent [Java Application] .8.0 261 Ibin\iavaw.exe (Nov 15, 2020, 
Hibernate: 
Hibernate: 
Hibernate: 
Hibernate: 
select 
select 
select 
select 
studentø 
studentø 
studentø 
studentø 
ret rived 
as 
as 
as 
as 
idl 
idl 
idl 
idl 
studentø 
studentø 
studentø 
studentø 
. email as emai12 
.email as emai12 
.email as emai12 
.email as emai12 
studentø 
studentø 
studentø 
studentø 
. first 
. first 
. first 
. first 
Objects 
Student 
Student 
Student 
Student 
Closing 
have been 
Cid=l, firstName=Sasuke, lastName=KvT, 
Cid=2, firstName=Kakashi, lastName=KvT, 
Cid=3, firstName=Itachi, lastName=KvT, 
Cid—$, firstName=Adarsh, lastName=KavtiyaI, 
the factory session 
orz.hidernste.enz• 
Ine. 
. connections . interns I .

Note: Below Hibernate v5.2 use “session.createQuery(“from Student”).list()” method as in above versions the method has been deprecated.

Update Object

9 public class updateStudent 
Ile 
public static void main (String[] args) { 
int studentld = 
// create session factory and a session 
SessionFactot"y factory = new 
. buildSessionFactoy(); 
try 
Session session = factory.getCurrentSession(); 
session . begin Transaction ; 
// Retrieving student object from the database instead of creating new one 
Student 
theStudent = session . get(Student.cIass, 
studentld) ; 
// update the name and email of student 
theStudent. " ) ; 
the object... 
// save the object in the memo-y 
session . saveOrUpdate(theStudent) ; 
// update all the specific column within the table 
// Student set .executeLlpdate(); 
session. Student set lastName= 
. executeLlpdate(); 
// commit the transaction 
session . getTransaction . commit() ; 
System. out. ("Id: " 
+ theStudent.getId() + 
where 
" have been updated.
Console X 
UpdateStudent [Java Application] Fil 
Hibernate: select studentø . id as idl 
Updating the object... 
Id: I have been updated. 
Closing the factory session. 
stut 
org.nisernste.engine.jd: 
:NFO: HHHIØØØIØØ8: Cleaning connection 'OOI

Delete Object

g public class DeleteStudent 
*Ile 
public static void main (String[] args) { 
int studentld = 
// create session factory and a session 
SessionFactot"y factory = new 
. buildSessionFactoy(); 
try 
Session session = factory.getCurrentSession(); 
session . begin Transaction ; 
the object..."); 
int result = session. from Student where ' 
System .out. ' 
+ result); 
// commit the transaction 
session . getTransaction . commit() ; 
+ studentld + 
" ) . executeupdate() ; 
(result a) { 
System. out. println ("Id: ' 
else 
System. out. ("Id: " 
catch (Exception 
studentld 
studentld 
' has been deleted. 
not found. 
No deletion operation performed ! ! " ) • 
save the data 
System error occured. 
e. printStackTrace(); 
finallv 
Cannot update or
Console X 
DeleteStudent [Java Application] File 
:NF0. 
. HHHØØØ115: 
Hi sernste connection size 
Using dislec+• nrg.nisernste.d 
Deleting the object... 
Hibernate: delete from Student where '5' 
result: I 
Id: 5 has been deleted. 
Closing the factory session. 
:NF0: HHHIØØØIØØ8: cleslinz J 
5001

Check out below git repo for a source code of this project:

https://github.com/AdarshKvT/hibernate-demo

Clone:

git clone https://github.com/AdarshKvT/hibernate-demo.git

Leave a comment