To Do List
- Add Hibernate Configuration file
- Annotate Java Class
- Develop Java Code to perform database operations

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

Two option for Mapping a class:
- XML config file (legacy approach)
- Java Annotations (modern, preferred)
- Map class to database table
- Map fields to database columns

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

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() ;](https://kvttechlead.home.blog/wp-content/uploads/2020/11/image-37.png?w=865)
Data inside MySql table

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

Some other type of ID generation Strategies

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

![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:](https://kvttechlead.home.blog/wp-content/uploads/2020/11/image-43.png?w=698)
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

![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 .](https://kvttechlead.home.blog/wp-content/uploads/2020/11/image-45.png?w=625)
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.](https://kvttechlead.home.blog/wp-content/uploads/2020/11/image-46.png?w=862)
![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](https://kvttechlead.home.blog/wp-content/uploads/2020/11/image-47.png?w=355)
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](https://kvttechlead.home.blog/wp-content/uploads/2020/11/image-48.png?w=871)
![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](https://kvttechlead.home.blog/wp-content/uploads/2020/11/image-49.png?w=337)
Check out below git repo for a source code of this project:
https://github.com/AdarshKvT/hibernate-demo
Clone: