Professional Documents
Culture Documents
FALLSEM2022-23 CSI3018 ETH VL2022230103646 Reference Material I 20-10-2022 CSI3018 Module 5
FALLSEM2022-23 CSI3018 ETH VL2022230103646 Reference Material I 20-10-2022 CSI3018 Module 5
Module – 5
Hibernate
1
SCOPE
CSI3018- Advanced Java
Outline
• Introduction
• Hibernate architecture
• Object Relation Mapping (ORM)
• Hibernate annotations
• Hibernate Query Language
• CURD application using Hibernate
2
SCOPE
CSI3018- Advanced Java
Introduction
Hibernate is a Java framework that simplifies the development of
Java application to interact with the database.
It is an open source, lightweight, ORM (Object Relational
Mapping) tool. Hibernate implements the specifications of JPA
(Java Persistence API) for data persistence.
What is ORM tool?
It is a technique that maps the object stored in the database.
An ORM tool simplifies data creation, manipulation, and access.
It internally uses the Java API to interact with the databases.
3
SCOPE
CSI3018- Advanced Java
Introduction
What is JPA?
Why Hibernate?
5
SCOPE
CSI3018- Advanced Java
Hibernate Features
Lightweight
Hibernate is a lightweight framework as it does not contains additional
functionalities; it uses only those functionalities required for object-relational
mapping.
It is a lightweight framework because it uses persistent classes for data transfer
between java application and databases.
6
SCOPE
CSI3018- Advanced Java
Hibernate Features
Auto-Generation
Hibernate provides a feature of automatic table generation. It means a
programmer need not worry about the query implementation, i.e., Hibernate
does on its own.
Lazy Loading
Hibernate supports a new concept called lazy loading. Lazy loading concept
retrieves the only necessary object for execution.
It also improves the performance of an application.
Database Independent
Hibernate is database-independent as it provides ‘Database Dialect’ so we need
not write SQL queries.
It supports many databases such as Oracle, MySql, Sybase, etc.
7
SCOPE
CSI3018- Advanced Java Hibernate Architecture
Hibernate is an ORM framework
with a layered architecture.
Application Layer
Hibernate Core Layer
Database Layer
8
SCOPE
CSI3018- Advanced Java
Hibernate Framework
9
SCOPE
CSI3018- Advanced Java Core Objects of the Hibernate Framework
1. Configuration
The org.hibernate.cfg package contains the Configuration class, which
consists of the properties and function files of Hibernate.
The configuration object is created only once during the application
initialization.
To activate the Hibernate Framework, we use the following code:
Configuration cfg=new Configuration();
2. SessionFactory
The org.hibernate.sessionFactory package contains the SessionFactory
interface whose object can be obtained by the object of Configuration class.
It is a threadsafe object and used by all the threads in the application.
4. Transaction
The org.hibernate.transaction package contains a Transaction interface.
The object of the session creates a Transaction object. It provides the instruction
to the database for transaction management.
12
SCOPE
CSI3018- Advanced Java
First Hibernate Example
13
SCOPE
CSI3018- Advanced Java
First Hibernate Example
Create the Persistent class
14
SCOPE
CSI3018- Advanced Java
First Hibernate Example
Create the Persistent class
Student.java
package com.mypackage; public String getName() {
return name;
public class Student { }
private long id;
public void setName(String name) {
private String name; this.name = name;
private String degree; }
15
SCOPE
CSI3018- Advanced Java
hibernate-mapping : It is the root element in the mapping file that contains all
the mapping elements.
class : It is the sub-element of the hibernate-mapping element. It specifies the
Persistent class.
id : It is the sub-element of class. It specifies the primary key attribute in the
class.
generator : It is the sub-element of id. It is used to generate the primary key.
There are many generator classes such as assigned, increment, hilo, sequence,
native etc.
property : It is the sub-element of class that specifies the property name of the
Persistent class.
16
SCOPE
CSI3018- Advanced Java
<property name=“name"></property>
<property name=“degree"></property>
</class>
</hibernate-mapping>
17
SCOPE
CSI3018- Advanced Java
18
</hibernate-configuration> SCOPE
CSI3018- Advanced Java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
19
SCOPE
CSI3018- Advanced Java
20
SCOPE
CSI3018- Advanced Java
Introduction
5. Load the jar file
For successfully running the hibernate application, you should have the
hibernate5.jar file.
21
SCOPE
CSI3018- Advanced Java
Configuration file
22
SCOPE
CSI3018- Advanced Java
Hibernate - O/R Mappings
Entity Association Mapping
The mapping of associations between entity classes and the
relationships between tables is the soul of ORM. In other words, it
specifies how the objects are associated with each other.
23
SCOPE
CSI3018- Advanced Java
O/R Association Mappings
One to One Mapping
only one object of a persistent class is related to only one object of another persistent
class.
Student.hbm.xml
<hibernate-mapping>
<class name="com.hibernate.Student" table="STUD1">
<id name="studentId" type="long" column="ID">
<generator class="increment" />
</id>
<property name="studentName" type="string" length="100"
not-null="true" column="name" />
<one-to-one name="address" class="com.hibernate.Address"
cascade="all" />
</class>
</hibernate-mapping>
24
SCOPE
CSI3018- Advanced Java
O/R Association Mappings
One to Many Mapping
A Set is a java collection that does not contain any duplicate element. A Set is
mapped with a <set> element in the mapping table and initialized with
java.util.HashSet. You can use Set collection in your class when there is no
duplicate element required in the collection.
25
SCOPE
CSI3018- Advanced Java O/R Association Mappings
One to Many Mapping
<hibernate-mapping>
<class name="com.hibernate.Student" table="student">
<id name="studentId" column="sutid">
<generator class="increment" />
</id>
<property name="studentName" column="stud_name" type="string" />
<set name="studentPhone" cascade="all">
<key column="stud_id" />
<one-to-many class="com.hibernate.Phone" />
</set>
</class>
</hibernate-mapping>
26
SCOPE
CSI3018- Advanced Java O/R Association Mappings
Many to One Mapping
It is one of the most commonly used association mapping.
In Hibernate, Many-to-One association mapping is applied from child class
object to parent class object.
<hibernate-mapping>
<class name="com.hibernate.Student" table="STUD1">
<id name="studentId" type="long" column="ID">
<generator class="increment" />
</id>
<property name="studentName" type="string" length="100"
not-null="true" column="name" />
<many-to-one name="studentAddress" class="com.hibernate.Address"
column="STUDENT_ADDRESS" cascade="all" />
</class>
</hibernate-mapping>
27
SCOPE
CSI3018- Advanced Java O/R Association Mappings
Many to Many Mapping
HQL queries are translated by Hibernate into conventional SQL queries, which in
turns perform action on database.
Advantages of HQL
Database Independent- HQL is a database-independent query language. That means if we
write programs using HQL commands, then the program can be executed in all relational
databases without any modification.
Case- insensitive for keywords- HQL is similar to SQL. Hence, their properties are also
identical. HQL is case-insensitive for keywords like SQL, which means all the keywords can
be written in both upper and lower case. For example, select, SELECT, and Select are all the
same.
Object-oriented- HQL is an object-oriented query language as it supports inheritance,
polymorphism, and association. Instead of real table names and columns, it uses class and
property names.
Easy to Learn- HQL is easy to learn and implement, as its syntax is identical to SQL.
29
SCOPE
CSI3018- Advanced Java
HQL Syntax
SELECT Clause
String hql = "SELECT from Employee";
Query query = session.createQuery(hql);
List results = query.list();
DELETE Clause
String hql = "DELETE FROM Employee " +
"WHERE id = :employee_id";
Query query = session.createQuery(hql);
query.setParameter("employee_id", 10);
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);
30
SCOPE
CSI3018- Advanced Java
HQL
INSERT Clause
UPDATE Clause
String hql = "UPDATE Employee set salary = :salary " +
"WHERE id = :employee_id";
Query query = session.createQuery(hql);
query.setParameter("salary", 1000);
query.setParameter("employee_id", 10);
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);
31
SCOPE
CSI3018- Advanced Java CRUD Application
public class Student{
public void insertStudent() {
Transaction transaction = null;
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
// start a transaction
transaction = session.beginTransaction();
// commit transaction
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
}
}
32
SCOPE
CSI3018- Advanced Java CRUD Application
public void updateStudent(Student student) {
Transaction transaction = null;
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
// start a transaction
transaction = session.beginTransaction();
// commit transaction
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace(); 33
} } SCOPE
CSI3018- Advanced Java CRUD Application
public void deleteStudent(int id) {
36
SCOPE