100% found this document useful (1 vote)
78 views45 pages

03-Hibernate Slide 2023-2

The document discusses topics related to Hibernate including basic annotations, relationships, caching, and the Hibernate architecture. It provides an overview of concepts like entities, primary keys, and the different methods available in Hibernate.

Uploaded by

atamyratm00
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
78 views45 pages

03-Hibernate Slide 2023-2

The document discusses topics related to Hibernate including basic annotations, relationships, caching, and the Hibernate architecture. It provides an overview of concepts like entities, primary keys, and the different methods available in Hibernate.

Uploaded by

atamyratm00
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

161-167 NT

Hibernate
21.06.2023
Basic annotation-Embbadable

LOG IN TO ZOOM LINK THROUGH LMS SYSTEM


Hibernate
Topics covered

• Basic Annotations (@Entity, @Table, @Id, • Fetch Types (LAZY, EAGER)


@Column etc…)
• Caches Level (First Level and Second Level)
• HQL (Hibernate Query Language)
• Details of the Get and Load method
• Embedded Annotations
• Hibernate Lifecycle, States: Transient,
• OneToOne Relation Persistent, Detached, Removed

• OneToMany Relation • Hibernate Session

• ManyToMany Relation • JPA entityManager


General Questions

What is Persistence?

What is JDBC?

What is ORM?

What is Hibernate?

What is JPA?
Persistent Data

OOP
(Java, C#, C++)

Persistent
CRUD Oper.
Data

DataBase
(RDMS, MySQL, SQL Server,
postgreSQL)
Object Relational Mapping (ORM)

Object Relational Mapping (ORM) is a technique used in creating a "bridge" between object-
oriented programs and, in most cases, relational databases. Put another way, you can see
the ORM as the layer that connects object oriented programming (OOP) to relational databases.

Java Object ORM


App Class (Object Relational
Mapping)

DATABASE

Popular ORM Tools for Java: Hibernate, Apache OpenJPA,


EclipseLink, JOOQ

INTERVIEW
Java Persistent API (JPA)

JPA stands for Java Persistence API (Application Programming Interface). It was initially released on 11
May 2006. It is a Java specification that gives some functionality and standard to ORM tools. It is used to
examine, control, and persist data between Java objects and relational databases. It is observed as a
standard technique for Object Relational Mapping.

Key features of JPA

Ø JPA is only a specification, it is not an implementation.


Ø It is a set of rules and guidelines to set interfaces for
implementing object-relational mapping
Ø It needs a few classes and interfaces.
Ø It supports simple, cleaner, and assimilated object-relational
mapping.
Ø It supports polymorphism and inheritance.
Ø Dynamic and named queries can be included in JPA.
Hibernate - JDBC

Hibernate is an open source Object-Relational Persistence and Query service for any Java
Application. Hibernate maps Java classes to database tables and from Java data types to
SQL data types and relieves the developer from most common data persistence related
programming tasks.

JDBC is acronym of Java Database Connectivity. It is used to connect your application to the
database and transactions . It is an open source Java API. Hibernate is also used for connect
your application to database and to do database related transactions but with different approach.

Java Object Hibernate


App Class
JDBC

DATABASE
Difference Between JDBC & Hibernate

JDBC Hibernate

It is database connectivity technology It is a framework

It does not support lazy loading It supports lazy Loading

Low performance High Performance

For Database Connectivity For object-relational mapping

We need to maintain explicitly database


Hibernate itself manage all transaction
connection and transaction.

No caching. We need to write code for Hibernates provides two types of caching :
implementing caching First level Cache Second level cache
INTERVIEW
Maven Dependency

<dependency>

<groupId>org.hibernate</groupId>
Maven dependency:
<artifactId>hibernate-core</artifactId>
In the context of Maven, a dependency is <version>5.6.10.Final</version>
simply a JAR file used by a Java application.
</dependency>
Based on the POM file, Maven will download
and add the JAR file to our Java path. Java will <dependency>
then be able to find and use the classes in the <groupId>org.postgresql</groupId>
JAR file. <artifactId>postgresql</artifactId>
<version>42.3.6</version>
</dependency>
How to create Hibernate project?

1. Create Maven Project


Maven is a popular open-source build tool developed by the Apache Group to build, publish, and deploy
several projects at once for better project management. The tool allows developers to build and
document the lifecycle framework.

2. Add dependencies into pom.xml file


ü Hibernate core
ü PostgreSQL connector
3. Hibernate Configuration
Ø Url, username, password, etc

4.Add Java Class & Annotate it


Ø @Entity, @Table, @Id, @Column, @Transient
Maven-How It Works?

C:\Users\your
po home\.m2\repository
re
c al
lo
ck ~/.m2/repository
he
2.C
pom.xml 1.read
4. Save in local Repo
<dependencies>
<……> 3.G
<……> 5. Build & Run et
<……> fro
m
Re
</dependencies m
ot
e
Re
po

Enjoy;)
@annotations

Java annotations are metadata (data about data) for our program source code. They provide additional
information about the program to the compiler but are not part of the program itself. These annotations
do not affect the execution of the compiled program. Annotations may also include elements
(members/attributes/parameters).
Annotations: @AnnotationName

Annotation Description

@Entity Defines that a class can be mapped to a table

@Table Specifies the details of the table that will be persist the entity

@Id Indicates the member field below is the PK of current entity

@Column Used for adding the column the name in the table of a particular DB

@Transient Used to ignore a field from serialization

@Embeddable It is an annotation to declare that a class will be embedded by other entities.


Some Hibernate Classes
1. Configuration Class
Used to define all configuration and mapping sources in one API and to then build the
SessionFactory in one-shot. The configuration and mapping sources defined here are just held
here until the SessionFactory is built.
2. SessionFactory

It is responsible for the creation of Session objects. The Hibernate Session provides methods such
as save, delete and update, all of which are used to perform CRUD-based operations on the
database to which the SessionFactory connects

3. Session Interface
The Session interface is the main tool used to communicate with Hibernate. It provides an API
enabling us to create, read, update, and delete persistent objects. The session has a simple
lifecycle.
4.Transaction Interface
Allows the application to define units of work, while maintaining abstraction from the
underlying transaction implementation
Hibernate Architechture

Mapping Info Transaction


beginTransAction()
addAnnotation()
buildSessionFactory() openSession()

Configuration SessionFactory Session Query


Configure() createQuery()

DB Info Criteria
createCriteria()
Hibernate Query Language

Hibernate Query Language (HQL) is an object-oriented query language, similar to SQL, but
instead of operating on tables and columns, HQL works with persistent objects and their
properties. HQL queries are translated by Hibernate into conventional SQL queries, which in
turns perform action on database.

String hql = "FROM s.name Student01 s WERE s.id > 1003 ORDER BY s.grade DESC";

NOTE:
Keywords like SELECT, FROM, and WHERE, etc., are not case sensitive, but
properties like table and column names are case sensitive in HQL.
@Embeddable and @Embedded

//Class 1 //RunnnerClass
l @Embeddable
l public class Address { Student student=new Student();
student.setId(1);
l private String street; Address address=new Address();
l private String city; address.set(street);
l private String country; .
.
l } student.setAddress(address);
//Class 2
l @Entity
l public class Student{
l @Id
l private int id
//Output
l @Embedded id name grade city country grade
l private Address address;
l }
Association Mappings in Hibernate

Entities can contain references to other entities, either directly as an embedded property or
field or indirectly via a collection of some sort (arrays, sets, lists, etc.). These associations are
represented using foreign key relationships in the underlying tables. These foreign keys
will rely on the primary ids used by participating tables.

One-to-One One-to-Many Many-to-Many Many-to-One

1 person has 1 passport 1 cart has many Items Many students likes Many books to a
many courses student
One-to-One Relationship

One to one represents that a single entity is associated with a single instance of the other
entity

l One Student can have an Diary entity


l Uni-directional and bi-directional

Foreign Key preserves relationship


between tables
Uni-Directional One-to-One Mapping

@Entity
public class Diary {
@Entity
@Id
public class Student {
private int id;
@Id
Uni Direction private String name;
private int id;
@OneToOne
private String name;
@JoinColumn
}
private Student student;

JoinColumn marks a column as a join column for an entity association or an element


collection.
With Uni-directional structure, just Diary can navigate the student.
Bi-Directional One-to-One Mapping

@Entity
@Entity
public class Diary {
public class Student {
@Id
@Id
private int id;
private int id;
Bi - Direction private String name;
private String name;
@OneToOne(mappedBy="student") @OneToOne

private Diary diary; @JoinColumn

} private Student student;

mappedBy signals hibernate that the key for the relationship is on the other side.
This means that although you link 2 tables together, only 1 of those tables has a foreign key
constraint to the other one.
Uni-Directional Many-to-One Relationship

A Many-to-One relationship is defined as a relationship between several instances of one entity


and one instance of another entity. For example, it is possible for more than one student to work
on a project.

l One University can have one or more Student

l One side of the association will have the reference to the other side.
l Navigation is only in one direction
Uni-Directional Many-to-One Relationship
Uni-Directional Many-to-One Relationship

@Entity
@Entity public class Student {
public class University @Id
{
private int id;
@Id
Uni Direction private String name;
private int id;
@ManyToOne
private String name;
@JoinColumn
}
private University university;

}
One-to-Many Relationship

In a one-to-many relationship, one record in a table can be associated with one or more records
in another table. For example, each customer can have many sales orders.

l One Student can have one or more Book entities

l One side of the association will have the reference to the other side.
l Navigation is only in one direction
134-135 DT
Hibernate
16.04.2023
OneToMany-ManyToMany
LOG IN TO ZOOM LINK THROUGH LMS SYSTEM
Uni-Directional One-to-Many Relationship

@Entity
public class Student {
@Entity
@Id
public class Book {
private int id;
@Id
Uni Direction private String name;
private int id;
@OneToMany
private String name;
@JoinColumn
}
private List<Book> bookList =
new ArrayList<>();
}
Bi-Directional One-to-Many Relationship

@Entity
@Entity
public class Book {
public class Student {
@Id
@Id
private int id;
Bi Directional private int id;
private String name;
private String name;
@ManyToOne
@OneToMany(mappedBy="student")
@JoinColumn
private List<Book> bookList
private Student student; = new ArrayList<>();
} }
Cascade Types

Cascading is a feature in Hibernate, which is used to manage the state of the mapped entity whenever
the state of its relationship owner (superclass) affected. When the relationship owner (superclass) is
saved/ deleted, then the mapped entity associated with it should also be saved/ deleted automatically.,
etc.).

@Entity
public class Student {
@Id

private int id;


private String name;

@OneToMany(mappedBy="student", cascade = CascadeType.ALL)

private List<Book> bookList = new ArrayList<>();


}
Cascade Types

CascadeType. Description

PERSIST save() or persist() operations cascade to related entities.

REFRESH This cascade type indicates that the refresh operation

MERGE related entities are merged when the owning entity is merged.

removes all related entities association with this setting when the owning
REMOVE entity is deleted.

DETACH detaches all related entities if a “manual detach” occurs.

ALL all is shorthand for all of the above cascade operations.


orphanRemoval

“orphanRemoval = true” deletes orphaned entities from the database. An entity that is no
longer attached to its parent is the definition of being an orphan. OrphanRemoval attribute can be
used in @OneToOne ve @OneToMany

!
@Entity
public class Student { l if parent object is deleted,
child object will be deleted
@Id also.
l If we set a null to the child
private int id;
object of the parent, child object
private String name; will be deleted.
student.getBookList().set(0,null)
@OneToMany(mappedBy="student", orphanRemoval = true) (will delete the book in the 0
index)
private List<Book> bookList = new ArrayList<>();
}
Many-to-Many Relationship

A many-to-many association is made between two entities where one entity can be
associated with multiple other instances of the other entity.

l One Student can have many Books


l One Book belongs to many Students
Many-to-Many Relationship

A many-to-many association is made between two entities where one entity can be
associated with multiple other instances of the other entity.

l Join Table provides a mapping between two tables.


l Join Table has foreign keys for each table to define the mapping relationship.
l Many to Many mapping can be unit and bi directional.
Many-to-Many Relationship
FetchType: Eager vs. Lazy

While loading the parent class object, it chooses whether to load a child class object. The fetching
method must be defined when using association mapping in Hibernate.

Lazy Eager

FetchType.LAZY – Fetch it when you need it FetchType.EAGER – Fetch it so you’ll have it when you need it

Default loading: ManyToMany, OneToMany Default loading: ManyToOne, OneToOne

Performance may be impacted if too much unneeded


Much faster initial loading than Eager Loading
data is loaded

INTERVIEW
@GeneratedValue

The @GeneratedValue annotation provides the specification of generation strategies for the primary keys
values.
The strategy attribute is used to specify the primary key generation strategy that the persistence provider
must use to generate the annotated entity primary key.

Strategy Description

Based on the database’s support for primary key generation framework decides
AUTO which generator type to be used.

In this case database is responsible for determining and assigning the next
IDENTITY primary key.

A sequence specify a database object that can be used as a source of primary


SEQUENCE key values. It uses @SequenceGenerator.

TABLE It keeps a separate table with the primary key values. It uses @TableGenerator.

! Note: Default value of Strategy attribute is AUTO. The preferred strategies are IDENTITY for MySQL, SQLite and
MsSQL and SEQUENCE for Oracle and PostgreSQL.
Criteria API

Criteria is a another technique of data retrieval apart from HQL and native SQL queries. The primary
advantage of the Criteria API is that it is intuitively designed to manipulate data without using any hard-coded
SQL statements.

CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<Student> criteriaQuery =
cb.createQuery(Student11.class);
Root<Student> root = criteriaQuery.from(Student.class);

//task: fetch students whose grade is less than 95


criteriaQuery.select(root).
where(cb.lessThan(root.get("grade"), 95));

Query<Student> query = session.createQuery(criteriaQuery);


List<Student> resultList = query.getResultList();
Hibernate Caching

Hibernate caching acts as a layer between the actual database and your application. It reduces the time taken to obtain the required
data — as it fetches from memory instead of directly hitting the database. It is very useful when you need to fetch the same kind of data
multiple times.

First Level Second Level Query


cache cache cache

by default the developer needs to the developer needs to


enabled by enable it explicitly enable it explicitly
Hibernate itself
get() vs load()
In hibernate, get() and load() are two methods which is used to fetch data for the given identifier. They both belong to
Hibernate session class. Get() method return null, If no row is available in the session cache or the database for the given
identifier whereas load() method throws object not found exception.

Proxy Obj
student student
Request
j bj id:
ob Id: 1 t o name: Id: 1
st name: Mark u es name: Mark
ue j q bj age:
Re
q b grade: 98 Re o Response grade: 98
seo o ns
e

load()
on sp
request get() R e sp request Re

with id:1 Re with id:1 Re


qu
qu student es Proxy Obj student
es to
Re to bj
sp bj Request
on id:
se
nu No data name: No data
ll
age:
onse
R esp

Will throw ObjectNotFoundException


get() vs load()

get() load()

It is used to fetch data from the database for the given It is also used to fetch data from the database for the given
identifier identifier

If object not found for the given identifier then it will return
It will throw object not found exception
null object

It returns fully initialized object so this method eager load


It always returns proxy object so this method is lazy load the object
object

It is slower than load() because it return fully initialized


It is slightly faster.
object which impact the performance of the application

If you are not sure that object exist then use get() method If you are sure that object exist then use load() method.

INTERVIEW
Object (entity) life cycle
Every Hibernate entity naturally has a lifecycle within the framework – it's either in a transient, persistent or managed,
detached or deleted state. Understanding these states on both conceptual and technical level is essential to be able to use
Hibernate properly.

1. New or Transient State 2. Persistent or Managed State


In order to convert or move an object from
When ever an object of a POJO class is
Transient to Persistent, there are two ways.
Created(instantiated) using the new operator
a) Saving the object to the database using
then it will be in the Transient state; this object
session
is not associated with any Hibernate Session.
b) Loading the object from the database
using session
Ex: Student student = new Student(”Tom Jerry",
Ex: session.save(student) or
98); // Transient
session.persist(student);

Save Load
persist get
new Transient Persistent
Transient State State State
Object (entity) life cycle continuing…

3. Detached State 4. Removed State

A persistent object is considered to be in the


In order to convert or move an object from
removed state when a delete() operation is
Persistence to Detached State, we need to
called on it. Note that Once you've deleted an
clear the cache of the session or close the
object and moved to the “removed” state, you
session by using following methods
should no longer use that particular object for
any reason.
Ex: session.clear(); or session.close()
Ex: session.delete(student);

Save
persist
Persistent Detached delete garbage
State State Persistent Removed
clear State State
close
University table Student table
id name student_id id name univ_id
1 Abc [1,4, 5, 7] 1 Aaa 1
2 Xyz [2, 3, 6, 8] 2 Bbb 2
3 Ccc 2
4 Ddd 1

You might also like