21/01/25 27/02/25
Hibernate
Hibernate is a java framework that simplify the development of java application to
interact with the relational databases.
It is an open sourced ORM (Object Relational mapping) tool which simplify the
complex join Query. It implements the specification of JPA (Jakarta persistence API)
for java application to database communication.
What is ORM?
It stands for object relational mapping which help java developer to persist the data
in a database with or without writing a SQL query.
It is responsible for managing the conversion of software object to interact with the
table column in a relational database. It converts java object in a database table. It
converts java object member or field into database table column. It create table
automatically with one database.
Advantages of Hibernate:
Open Source
Fast performance
It supports database independent query
Automatic table creation & simplifies complex join query
Different ORM tools
1. Hibernate
2. Top Link
3. Eclipse link
4. Open JPA
5. MyBetis or Ibetis
Q. What is JPA (Jakarta persistence API) or (Java Persistence Api)
It is a Jakarta persistence API which is a java specification. It is used to persist
data between java objects and relational databases, with the help of multiple
classes and interfaces.
All the classes and interfaces are present inside Jakarta.persistence package
for newer version & javax.persistence package for older version.
JPA acts as a bridge between object oriented domain models (Business logic)
and relational database system. It is capable for various database operation
such as CRUD operation.
Q. What is java version you are using? (QIQ)
Java version is 23 Compiler version is 17
05/03/25
What are Annotations?
It is a set of code or instruction which provide some additional information to java
compiler to perform specific tasks.
There are multiple types of annotations: class, variable, method level annotation.
Annotation:
1. @Entity: It is a class level annotation which is used to declare the class as an
entity class Because of this annotation the java object will get converted into
database table.
2. @Id: This is a variable level annotation which is used to convert that variable
into table primary key.
3. Note: @Entity & @Id both are interdependent
4. @Table(name = “name of the table”): This is a class level annotation which is
used to provide the table name from programmer side.
5. @column(name=”columnName”,nullable=true/false, length = “”): This is a
variable level annotation which is used to provide extra validation for table
column & column name as well.
6. @GeneratedValue(stratergy = GenerationType.Identity): This is a variable
level annotation which is used to declare column as auto increment column.
7. @joinColumn(name=””): -
It is a reference label annotation which is used to change the foreign key
column name from developer side.
We write this annotation at the top of dependent object reference variable in
one-to-one mapping, many-to-one mapping.
It always denotes the current object reference is a dependent object.
Mapping annotation of Hibernation:
1. @onetoone: This is a reference variable level annotation. It is used to connect
one table with another table with the help of primary key and foreign key.
2. @onetomany:
3. @manytoone:
4. @manytomany:
What is Lombok?
It is a java library which provides multiple annotations to reduce boilerplate code
such as getters, setters, toString(), hash code and equals.
Lombok Annotation:
@Getter: It is a class level or field (variable) level annotation.
@Setter: It is also a class level or field (variable) level annotation. @Data
@equalsandhashcode:
@toString():
@AllArgsConstructor():
@NoArgsConstructor
22/01/25 10/03/25
Classes and interfaces of JPA
Interfaces
1. EntityManagerFactory = It is present in Jakarta.persistence package. It is a part of
JPA which is used to provide the object to EntityManager interface with the help of
its method createEntityManager(String). It is also used to read connection from
persistence.xml file to java code.
EntityManager em = emf. createEntityManager()
2. EntityManager = It is present in Jakarta.persistence package. The EntityManager
provide object to EntityTransaction interface with the help of its method
getTransaction(). It is used to provide multiple inbuild methods to perform CRUD
operation such as:
a. persist(Object ob):void [It is used to execute INSERT Query),
Note: We can only persist/ insert a single object at a time but if we have to
persist multiple objects then we should go with for-each loop.
b. remove(Object ob):void [It is used to execute DELETE Query),
c. merge(Object ob):void [It is used to execute UPDATE Query),
d. find(ClassFileName(T.class), primary_key_value):T [It is used to execute
SELECT Query with where clause).
It also provide methods to create and execute JPQL ((Jakarta Persistence Query
Language), native/SQL queries. Those methods are:
a. createQuery(String Query):returns Query(I) [This method is for JPQL Query].
b. createNativeQuery(String Query, classfilename): returns Query(I) [This
method is to execute SQL/ native query].
EntityTransaction et = em.getTransaction()
3. EntityTransaction = This is used to begin the transaction and commit the
transaction by using begin() and commit() methods.
Note: It works for DML operation only.
Classes
1. Persistence(C): It is a class which is present in Jakarta.persistence package which is
used to read JDBC connection from persistence.xml file with the help of
createEntityManagerFactory(String persistenceUnitName) method & It provides
object to EntityManagerFactory.
EntityManagerFactory emf = Persistence.
createEntityManagerFactory( “persistenceUnitName”)
24/01/25 17/03/25
What IS JPQL?
It stands Jakarta persistence Query Language. It is a platform independent object
oriented query language defined as a part of Jakarta persistence api specification.
JPQL is used to communicate with entity classes and not with the table. JPQL is
inspired by SQL. It is faster than SQL. It is used for SELECT, UPDATE & DELETE QUERY.
To read and execute JPQL query we use createQuery() method from entity manager.
Syntax to create JPQL query:
SELECT Query
from EntityClassName, (without where clause)
or
Select aliasname from EntityClass aliasName
Select aliasname from EntityClass aliasName where aliasName.attributeName
=? (with Where clause)
To write JPQL Query with where clause hibernate provides Query Parameters:
27/01/25 18/03/25
Types of Query parameters:
Similar to JDBC preparedStatements parameters, JPA specifies two different ways to
write parametrized queries such as:
1. Positional Parameters 2. Named Parameters
Note: To execute select with where clause we always use Positional or Named
Parameters query.
setParameter() To set the value at the placeholder position we use setParameter()
of Query interface.
setParameter(int position, Object value) [Positonal]
setParameter(String value, Object value) [Named]
28/01/25 19/03/25
Native Query: It is also known as SQL query which directly communicate with the
database table.
To read and execute native query we use createNativeQuery(“Query”,Object.class)
method. It is a method of entityManager Interface. The return type for native query
is Query Interface.
For INSERT, UPDATE & DELETE we use Native query.
For SELECT, UPDATE & DELETE we use JPQL.
Q1. What is JPQL and why we use it?
Q2. What is Native Query and why we use?
Q3. Types of Query Parameters?
Mapping:
It is also known as association. The association between two java object or java
entity classes with the help of has-a-relationship is known as Mapping.
OR
The association between more than one table with the help of primary key & foreign
key is known as Mapping.
There are Two types of mapping in hibernate:
1. Unidirectional Mapping: The association from one side between more than one
entity class.
E.g., Student Subject
Subject is dependent on dependent which means that without student
subject cannot exists.
Also the table containing the foreign key is main object i.e., in this case it is
student.
Types of Unidirectional Mapping:
a. One to One mapping
b. One to Many mapping
c. Many to One mapping
d. Many to Many mapping
a. One to One Unidirectional Mapping:
We can achieve one to one unidirectional mapping with the help of
@onetoone annotation. In this mapping one object can connect with only one
object.
For e.g.,
Person (Object1) adhaar (Object2)
bankaccount(Object1) pancard (Object2)
country capital
b. One to Many Unidirectional Mapping:
Association Between more than one object where one object is connected
with multiple objects from one side is known as One To many Unidirectional
Mapping.
For e.g.,
University(Entity 1) Colleges(Entity 2)
Country(Entity 1) States(Entity 2)
person(Entity 1) bank accounts(Entity 2)
c. One to Many Unidirectional Mapping:
Multiple object are connected with a single object.
For e.g.,
Subjects(Entity 1) Student(Entity 2)
Branches(Entity 1) Colleges(Entity 2)
@Entity
class Branch{
@Id
int id;
String name;
String buildingname; Branch
Id name Building College_id
@manytoone name
College college; 123 XYZ A block 133
124 ABC B block 133
}
@Entity
class College{ id name type address
@Id 133
132
int id;
134
String name;
String email;
String address;
String type;
}
27/03/25
d. Many to Many Unidirectional Mapping:
In this multiple object is connected with multiple objects.
E.g., Do the project Trainer & Student.
Cascading HIBERNATE
Cascading is feature in hibernate which is use to manage the state of the
dependent entity class. When we are performing some DML operation with
independent entity class the same action will be applied to the depended
entity class.
Note: If we perform some action (DML operation) on the target entity the
same action will be applied to the associated entity.
Types of Cascading
1. All JPA specific cascade operation are present or represented by
jakarta.persistence.cascade type where cascade type is enum and it
contains multiple final variables.
2. ALL, PERSIST, MERGE, REMOVE, REFRESH, DETACH
CascadeType.All – When we use all it means all the dml operations will
be performed with dependent object when programmer target the
independent object.
CascadeType.Detach –
What is detach state?
It refers to the state of an entity class that was previously
associated with a hibernate session but it is no longer associated
with it.
When entity class becomes detached, then it will exist as a
normal java object.
Usage:
As we know cascading is used to perform operation on multiple
tables but if we don’t want to perform operation on the other
table we make its state detach.
Lifecycle of entity class:
Transient state: Entity class as we created but it is not associated with
hibernate session. Transient object is not managed by hibernate and
database.
Persistence state: When the entity class associated with hibernate
session then it will be in persistence state. Hibernate session tracks the
entity class changes & same changes synchronized with the database.
Detach state: When the entity class persist inside the database & the
session of hibernate will get close and the same entity class will be
evicted from the hibernate session & will go into detached state.
Remove state: When the entity class deleted from the session and
deleted from the database then it will be in remove state.
Object session.begin Persiste session.commit
nce Detach
created
state state
in heap
Q. Difference between transient and detach?
2. Bidirectional Mapping: The association from both side between more than one
entity class.
a. One to One Bidirectional Mapping:
Q. What is mappedBy?
Ans. It is an attribute which is used in bidirectional mapping. It indicates that
the entity class is non-owning side and delete the foreign key column from that
particular table.
In the above example as you can see in the adhar entity class mapped by
attribute is used creating it a non-owning side and deleting the adhar foreign key.
Q. What is @JoinColumn(name= “” reference variable)
It is used to indicate that the particular enity class is an owning side and the
reference is an non-owning side.
It is used to change the foreign key column name in the current entity class.