Good Practices on Hibernate

Download Report

Transcript Good Practices on Hibernate

Object Relational Mapping
Contact: [email protected]
http://www.lalitbhatt.com
1
Persistence

Persistence
 Capability to preserve data beyond the lifecycle of an
application.

Relational concept of data management first introduced by E.F.
Codd in 1970 has proven to be the best way of managing
persistence.
http://www.lalitbhatt.com
2
Persistence using Java

Most of non trivial application needs a persistence mechanism
to store the data. This is true for Java based systems also.

Java based systems follow OO paradigm and have to deal with
Relational paradigm to interact with database.

At low level JDBC helps us in dealing with database however
this is a non OO way of handling databases which brings
mismatch also known as OO-Relational impedence.
http://www.lalitbhatt.com
3
Why ORM





Leakage of concern – Persistence is a cross cutting concern so
should not leak into domain model.
ORM provides transparent and automated persistence.
ORM does not require any interface to be implemented or any
super class to be extended.
Persistent class can be reused outside persistence context as
they are simple POJO’s. This helps in moving data to and from
UI layer and improves testability.
ORM provides transparent persistence. The persistent class are
not responsible for the persistence behavior. There job is
capture the domain data.
However ORM also do not provide complete transparent
persistence, though the impact is minimal
http://www.lalitbhatt.com
4
ORM

Object Relational Mapping
Sql for
update/insert
save objects
Relational
Database
ORM
OO World
objects
Result
Set
http://www.lalitbhatt.com
5
Object relational mismatch




Granularity
Sub Types
Polymorphism
Inheritance
http://www.lalitbhatt.com
6
Object relational mismatch

Granularity
User
USER
NAME
STREET
CITY
Address
http://www.lalitbhatt.com
7
Object relational mismatch


SubTypes
Inheritance and Polymorphism
User
Customer
Employee
http://www.lalitbhatt.com
8
Object relational mismatch
Identity
 In database the identity is maintained by primary key.
 In Java identity is maintained as equivalent to Object
equality or overriding equals method.
 Database has only one row at any point of time to
represent a record.
 In Java there might be multiple objects at the same time
representing the same notion of data.
http://www.lalitbhatt.com
9
Object relational mismatch


Associations : In OO-world association is maintained using
references but in Relational world association is maintained
using foreign key references.
In OO-world association are unidirectional. If bidirectional
association needs to be maintained, than references need
to be kept on both side.
http://www.lalitbhatt.com
10
Object relational mismatch

Data Navigation: In Java navigation can be done by
navigating the relationships, whereas in relational world we
need joins to reach to particular set of data.
http://www.lalitbhatt.com
11
ORM tools



ORM tools propose to solve this mismatch problem.
They provide the OO-world semantics to develop and take
care of mapping the data to relational semantics.
They provide flexibility to work with more than one
databases by taking care of vendor specific features.
http://www.lalitbhatt.com
12
ORM tools Feature Set




Provide API for basic CRUD operation.
Query language.
Mapping mechanism between classes and tables and
relationships.
Other features like dirty checking, lazy association fetching.
http://www.lalitbhatt.com
13
Hibernate vs JPA



JPA stands for Java Persistence API
Hibernate supports JPA and is an implementation provider
Hibernate has its own set of api’s
http://www.lalitbhatt.com
14
Good Practices on Hibernate


Handle relationships carefully: Build bidirectional if it is
needed.
Have an eye on your session size.
http://www.lalitbhatt.com
15
Good Practices on Hibernate


Lazy loading
Get vs Load
Persistence Context
Student
proxy
http://www.lalitbhatt.com
16
Good Practices on Hibernate



Lazy loading of collections
By default all associated entities and collections aren’t
initialized.
A collection can be eagerly loaded always
@OneToMany(fetch= FetchType.EAGER)
public Collection<PhoneEntity> getPhoneEntityList() {
return phoneEntityList;
}
http://www.lalitbhatt.com
17
Good Practices on Hibernate


Disabling Proxies
Proxies can be disabled for a class
@Entity(name="Student")
@org.hibernate.annotations.Proxy(lazy=false)
public class Student {



Usually a bad idea if using hibernate
JPA does not have any concept of proxies.
Disabling proxies will make the collection of student to also
load eagerly.
http://www.lalitbhatt.com
18
Good Practices on Hibernate
Fetching Strategies



Fetching in batches
Will issue a query for each phoneEntity list
Batch size can be used to reduce the number of hits to
database
Specifying batch
@Entity
@org.hibernate.annotations.BatchSize(size=10)
public class PhoneEntity {
http://www.lalitbhatt.com
19
Good Practices on Hibernate
Fetching Strategies

Subselect can force all the collections to load in
one shot, whenever you initialize the first
collection
@OneToMany( cascade={CascadeType.ALL})
@org.hibernate.annotations.Fetch(
org.hibernate.annotations.FetchMode.SUBSELECT
)
public Collection<PhoneEntity> getPhoneEntityList() {
return phoneEntityList;
}
http://www.lalitbhatt.com
20
Good Practices on Hibernate
Fetching Strategies

Select mode will bring all the data in one select.
@OneToMany( fetch = FetchType.EAGER)
public Collection<PhoneEntity> getPhoneEntityList() {
return phoneEntityList;
}



Uses outer join
If we have another collection set at SELECT in PhoneEntity class
it will lead to Cartesian problem
The depth of fetch is determined by max_fetch_depth
http://www.lalitbhatt.com
21
Good Practices on Hibernate
Fetching Strategies

Select mode will bring all the data in different select.
@OneToMany( cascade={CascadeType.ALL})
@org.hibernate.annotations.Fetch(
org.hibernate.annotations.FetchMode.SELECT
)
public Collection<PhoneEntity> getPhoneEntityList() {
return phoneEntityList;
}
http://www.lalitbhatt.com
22
Good Practices on Hibernate
Fetching Strategies

Collection can be fetched eagerly while there mapping is lazy =
true
select s from Student s left join fetch s.phoneEntityList
This is the preferred way to handle collections
http://www.lalitbhatt.com
23
Good Practices on Hibernate
Caching

Good candidates for caching
 Data that changes rarely
 Non critical data
 Data that is local to the application and not shared
http://www.lalitbhatt.com
24
Thank you
http://www.lalitbhatt.com
25