Hibernate
Hibernate
HIBERNATE
WITH JPA
DRAWBACKS OF JDBC
1
3/30/2023
WHAT IS HIBERNATE?
WHY HIBERNATE?
1. Hibernate Reduces lines of code by maintaining object-table mapping itself and returns result to
application in form of Java objects.
2. Hibernate does the implementation internally like writing queries & Establishing connection etc.
3. Hibernate removes a lot of boiler-plate code that comes with JDBC API, the code looks more
cleaner and readable.
4. Hibernate supports inheritance, associations and collections. These features are not present with
JDBC API.
5. JDBC is database dependent i.e. one needs to write different codes for different database.
Whereas Hibernate is database independent and same code can work for many databases with
minor changes.
6. Automatic SQL Query Generation. There is no problem of remembering sql queries.
2
3/30/2023
ORM
1. ORM is an acronym of OBJECT-RELATIONAL MAPPING.
2. ORM acts as a converter between java object and a database.
3. ORM Handles the logic required to interact with databases.
4. You write less code when using ORM tools than with SQL.
5. There are some popular ORM tools:
• Hibernate
• TopLink
• Eclipse Link
• Open JPA
• MyBatis (ibatis)
6. The most used ORM tool is Hibernate.
7. The ORM tool internally uses the JDBC API to interact with the database
JPA
1. JPA is a acronym of JAVA PERSISTENCE API.
2. JPA is a specification, not an implementation.
3. It is the standard application programming interface that makes database operations simple for
developers to carry out.
4. Hibernate is an implementation of the Java Persistence API (JPA).
5. A JPA (Java Persistence API) is a specification of Java which is used to access, manage, and persist
data between Java object and relational database.
6. As JPA is a specification it does not perform any operations by itself ,thus it requires
implementation so ORM tools like Hibernate, ibatis, Toplink, EclipseLink implements JPA
specification for data persistence.
7. JPA specification is same for all the ORM tools and it follows same standards ,so in the future if we
want to switch our application from one ORM tool to another then we can do it easily.
3
3/30/2023
It uses JPQL (Java persistence query language)as a It uses Hibernate query language(HQL) to perform
object oriented programming language to perform database operations
database operations
To interconnect with the entity manager factory for the To create Session instances, it
persistence unit, it uses EntityManagerFactory interface. uses SessionFactory interface
Thus, it gives an entity manager
It uses EntityManager to perform crud operations like It uses Session interface to perform crud operations
create, update, delete, read
4
3/30/2023
ENTITYMANAGER
• persist(Object entity): It is used to insert the data into database (acts as insert query)
• merge(Object entity): it is used to update the data into the database based on primary key
(NOTE: if the PK is available in the database it acts as update query ,else It acts as insert query)
• remove(Object entity): It is used to delete the data from the database.(acts as delete query)
• find(Class<T> entityClass, Object primaryKey): It is used to fetch the single data based on primary
key from the database(it acts as select query with where condition as PK)
ENTITYTRANSACTION
• void commit() - Commit the current resource transaction, writing any unflushed changes to the
database.
• The EntityManager.getTransaction() method returns the EntityTransaction interface.
5
3/30/2023
persistence.xml File
• The persistence. xml file is a standard configuration file in JPA
• It has to be included in the META-INF directory
• The persistence.xml file must define a persistence-unit with a unique name
• The persistence.xml file is used to configure Entity classes, provide database driver, database connection
information and other relational mapping details
• The persistence.xml file is created inside:
src/main/resources
META-INF(Folder)
persistence.xml(File)
Persistence
name.
• EntityManagerFactory emf=Persistence.createEntityManagerFactory(“pun”);
6
3/30/2023
HAS-A-RELATIONSHIP
• To map the java objects to Relational table we make use of some Annotations.
• In JDBC we use to create a table but in hibernate creation of table is done by using a annotation called
@Entity.
• To make any attribute as Primary key annotate it with @Id
• Entity: Creation of table
• Id: To make the given attribute has primary key
Example:
Entity Class
//create class Employee
@Entity
Table
class Employee{ id name salary
@Id
1 Ram 10000
private int id;
private String name; 2 Arun 3000
private double salary;
//getters and setters
}
MAPPING
7
3/30/2023
OneToOne-Unidirection
//create a class Person
@Entity //create a class Passport
class Person{
@Entity
@Id 1 1
private int id;
class PassPort{
private String name; @Id
private String address; private int pid;
@onetoone private String name;
private Passport passport; private long phone;
//getters and setters //getters and setters
}
OneToMany-unidirection
//create class Company //create class Employee
class Company{ class Employee{
@Id @Id
private int id; private int id;
private String name; 1 n private String name;
private String address; private String email;
@onetomany private String password;
private List<Employee> //getters and setters
employee;
//getters and setters
8
3/30/2023
ManytoOne-unidirection
ManytoMany-unidirection
person_language
id name Address id name origin
p_id l_id
10 arun Blr 1 Kannada Karnataka
10 1
20 rajath chn 2 Telugu Andhra
10 2
3 Tamil Tamilnadu
20 1
20 2
20 3
9
3/30/2023
OneToOne-bidirection
//create a class Person //create a class Aadhar
@Entity @Entity
class Person{ class Aadhar{
@Id 1 1 @Id
private int id; private int id;
private String name; private String name;
private String address; private long phone;
@onetoone @onetoone
private Aadhar aadhar; private Person person;
//getters and setters //getters and setters
}
OneToOne-bidirection
//create a class Person //create a class Aadhar
@Entity @Entity
class Person{ class Aadhar{
@Id 1 1 @Id
private int id; private int id;
private String name; private String name;
private String address; private long phone;
@onetoone(cascade=Cascade @onetoone(mappedBy=“aadhar")
Type.ALL) private Person person;
@JoinColumn //getters and setters
private Aadhar aadhar;
//getters and setters
}
10
3/30/2023
OneToMany-bidirection/ManyToOne-bidirection
//create class Company //create class Employee
class Company{ class Employee{
@Id @Id
private int id; private int id;
private String name; 1 n private String name;
private String address; private long phone
@onetomany @manytoone
private List<Employee> private Company company;
employee; //getters and setters
//getters and setters
11
3/30/2023
OneToMany-bidirection/ManyToOne-bidirection
ManytoMany-bidirection
//create class Person //create class Language
class Person{ class Language{
@Id @Id
private int id; private int id;
private String name; n 1 private String name;
private String address; private String origin;
@ManyToMany @ManyToMany
private Language language; private List<Person>person;
//getters and setters //getters and setters
id name address id name origin id name origin id name address
10 arun Blr 1 Kannada KAR 1 Kannada KAR 10 arun Blr
20 rajath chn 2 Telugu AP 2 Telugu AP 20 rajath chn
p_id l_id l_id p_id
10 1 1 10
10 2 1 20
20 1 2 10
20 2 2 20
person_language language_person
12
3/30/2023
ManytoMany-bidirection
13
3/30/2023
FETCH TYPES
• FetchType. In general, FetchMode defines how Hibernate will fetch the data.
• FetchType defines whether Hibernate will load data eagerly or lazily.
• Fetch type supports two types of loading: Lazy and Eager.
• FetchType.EAGER: When Hibernate fetch the data from owning side, both owning side and non-owning
side data will get fetched this type of Fetch Type is called as FetchType.EAGER.
• FetchType.LAZY: When Hibernate fetch the data from owning side, only owning side data will be fetched
non-owning side will be not fetched so this type of FetchType is called as FetchType.LAZY.
CASCADE
• CASCADE: It is the feature provided by hibernate to automatically manage the state of mapped
entity(non-owning side) ,whenever the state of owner entity(owning side) is affected.
• In other words, whatever the modifications like persist, merge, delete is done at owning side will get
affected to non-owning side.
• Cascading is done only at the owning side.
• To achieve cascading there are some cascade types:
1. CascadeType.PERSIST: Whenever the programmer saves the owning side, automatically non-owning
side will also be saved.
2. CascadeType.MERGE: : Whenever the programmer updates the owning side, automatically non-owning
side will also be updated.
3. CascadeType.REMOVE: Whenever the programmer deletes the owning side, automatically non-owning
side will also be deleted.
4. CascadeType.ALL: cascade type all is shorthand for all of the above cascade operations.
14
3/30/2023
GENERATED VALUE:
• Hibernate supports some generation strategies to generate a primary key in the database table.
• @GeneratedValue: This annotation is used to specify the primary key generation strategy to use. i.e Instructs
database to generate a value for this field automatically. If the strategy is not specified by default AUTO will be used
• @GeneratedValue annotation takes two parameters strategy and generator.
• If we want to automatically generate the primary key value, we can add the @GeneratedValue annotation. This can use
four generation types: AUTO, IDENTITY, SEQUENCE and TABLE.
• GenerationType.AUTO: Indicates that the persistence provider should pick an appropriate strategy for the particular
database
• GenerationType. IDENTITY: Indicates that the persistence provider must assign primary keys for the entity using a
database identity column
• GenerationType. SEQUENCE: Indicates that the persistence provider must assign primary keys for the entity using a
database sequence
• GenerationType. TABLE: Indicates that the persistence provider must assign primary keys for the entity using an
underlying database table to ensure uniqueness
CACHING
• Caching is a mechanism to enhance the performance of a system. It is a buffer memory that lies between
the application and the database. Cache memory stores recently used data items in order to reduce the
number of database hits as much as possible.
• There are mainly two types of caching: First Level Cache, and. Second Level Cache
• First Level Cache: This is a mandatory cache which is present by default in hibernate. All the request
objects passes through this cache. This cache can be utilized by application by sending many session
objects. All the cache objects will be stored until one session is open. Database tries to minimize the
number of hits to database in case there are many update statements commanded using session cache.
Once the session is ended this cache is also cleared and the objects its holding are persisted,
committed or disappeared without any updating depending upon the time of session closing.
• It is temporary memory.
select
entitymanager.find(2);
id=2
db
entitymanager.find(2);
CACHE MEMORY
15
3/30/2023
Second Level Cache:First of all, second level cache is not enabled by default in Hibernate you have to explicitly
enable it. To enable second level cache add Ehcache dependency in pom.xml.
• The second-level cache is accessible by the entire application means data hold by SessionFactory can be accessible to all
the sessions. once the session factory is closed all the cache associated with that is also removed from the memory
db
entitymanager2.find(2); Id=2
Id=10 select
entitymanager.find(10); Id=10
• When hibernate session try to load an entity, it will first find into the first-level cache, if it does not found then it will look
into the second-level cache and return the response (if available), but before returning the response it will store that
object/data into first-level also so next time no need to come at the session-level. When data is not found in the second
level then it will go to the database to fetch data. Before returning a response to the user it will store that object/data into
both levels of cache so next time it will be available at cache stages only.
LIFECYCLE OF HIBERNATE
Transient state
persist()
merge()
remove() Removed
Garbage
Object Persistent state state collector
detach() persist()
merge()
Detached state
16
3/30/2023
THANK YOU
17