03-Hibernate Slide 2023-2
03-Hibernate Slide 2023-2
Hibernate
21.06.2023
Basic annotation-Embbadable
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.
DATABASE
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.
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.
DATABASE
Difference Between JDBC & Hibernate
JDBC Hibernate
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?
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
@Table Specifies the details of the table that will be persist the entity
@Column Used for adding the column the name in the table of a particular DB
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
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.
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
@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;
@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
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
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 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
CascadeType. Description
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.
“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.
A many-to-many association is made between two entities where one entity can be
associated with multiple other instances of the other entity.
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
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.
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);
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.
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
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
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.
Save Load
persist get
new Transient Persistent
Transient State State State
Object (entity) life cycle continuing…
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