Hibernate is an object-relational mapping tool that allows Java objects to be persisted to a relational database. It provides transparent persistence by handling all database operations like insert, update, delete, and retrieval. Hibernate sits between the Java application and database, mapping objects to database tables and allowing developers to work with objects rather than directly with SQL statements. Configuration files define the mappings between Java classes and database tables. Hibernate uses these mappings to automatically generate SQL to load and store objects.
Hibernate is ORM
Hibernateis an Object to Relational
Mapping Tool
www.SunilOS.com 2
Object
ID NAME Salary
1 Ram 1000
2 Shyam 1100
3 Vijay 1200
4 Jay 1300
Object
Object
Object
3.
www.SunilOS.com 3
Object toRelational Mapping
USERS
oID
oFIRST_NAME
oLAST_NAME
oLOGIN_ID
oPASSWORD
public class User {
private int id = 0;
private String userId = null;
private String password = null;
private String firstName = null;
private String lastName = null;
public User(){}//Def Constructor
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
..Other Setter/Getter POJO (Plain Old Java
Object)
Data Transfer Object
(DTO)
Value Object ( VO)
• Class will become Table
• Attributes will become columns
• Instances will become Records
4.
POJO
Are persistent classes.
Representdomain model.
Identifier Property (optional) has PK of a
table.
Must have default constructor.
Accessor methods will have naming
convention setName, getName, isName.
Properties need not to be public
www.SunilOS.com 4
www.SunilOS.com 8
Configuration :hibernate.cfg.xml
<!--Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<mapping resource=“in/co/sunrays/dto/User.hbm.xml" />
<mapping resource=“in/co/sunrays/dto/Role.hbm.xml" />
</session-factory>
</hibernate-configuration>
9.
www.SunilOS.com 9
Configuration
1. CreateA Java Project from Eclipse
2. Add Hibernate Capabilities
3. Insert Database (MySQL) Driver into Build
Path
4. Create User.java
5. Create User.hbm.xml in same directory
with User.java
6. Keep hibernate.cfg.xml in the root
source folder
10.
www.SunilOS.com 10
TestUser -Add
public static void testAdd() throws Exception {
User pojo = new User ();
pojo.setFirstName("Dheeraj");
pojo.setLastName("Dubey"); //Prepare POJO
...
SessionFactory sessionFactory = new Configuration().configure()
.buildSessionFactory(); //Load Factory
Session s = sessionFactory.openSession(); //Create Session
Transaction tx = s.beginTransaction();
s.save(pojo); //Save POJO
tx.commit();
s.close();
}
11.
www.SunilOS.com 11
TestUser -Update
public static void testUpdate() throws Exception {
User pojo = new User ();
pojo.setId (4);
pojo.setFirstName("Dheeraj");
pojo.setLastName(“Upadhyay"); //Prepare POJO
...
SessionFactory sessionFactory = new Configuration().configure()
.buildSessionFactory(); //Load Factory
Session s = sessionFactory.openSession(); //Create Session
Transaction tx = s.beginTransaction();
s.update(pojo); //Update POJO
tx.commit();
s.close();
}
12.
www.SunilOS.com 12
TestUser -Delete
public static void testDelete() throws Exception {
User pojo= new User();
pojo.setId (4);
...
SessionFactory sessionFactory = new Configuration().configure()
.buildSessionFactory(); //Load Factory
Session s = sessionFactory.openSession(); //Create Session
Transaction tx = s.beginTransaction();
s.delete(dto); //Delete POJO
tx.commit();
s.close();
}
13.
www.SunilOS.com 13
TestUser -Get
public static void testGet() throws Exception {
SessionFactory sessionFactory =
new Configuration().configure().buildSessionFactory();
//Load Factory
Session s = sessionFactory.openSession(); //Create Session
User pojo = (User) s.get(User.class, 4);
System.out.println(pojo.getId());
System.out.println(pojo.getFirstName());….
s.close();
}
14.
www.SunilOS.com 14
Authenticate User
publicUser authenticate(String login, String pwd) throws
UserNotFoundException{
SessionFactory sessionFactory =
new Configuration().configure().buildSessionFactory();
Session s = sessionFactory.openSession();
Query q = s.createQuery(
"from User where userId = ? and password = ? ");
q.setString(0, login);
q.setString(1, pwd); Class
Name
Attributes
15.
www.SunilOS.com 15
Authenticate User
…
Listlist = q.list();
if (list.size() == 1) {
pojo = (User) list.get(0);
}else{
throw new
UserNotFoundException("login.invalid.user");
}
s.close();
return pojo;
}
16.
www.SunilOS.com 16
Get thelist of Users
public static void testList() throws Exception {
SessionFactory sessionFactory = new Configuration().configure()
.buildSessionFactory();
Session s = sessionFactory.openSession();
Query q = s.createQuery("from User");
List l = q.list();
Iterator it = l.iterator();
User pojo;
while (it.hasNext()) {
pojo = (User) it.next();
System.out.println(pojo.getId());
System.out.println(pojo.getFirstName());
}
s.close();
}
17.
www.SunilOS.com 17
Sequence Diagram
TestUserUser SessionFactory
Hibernate.cfg
.xml
Session
User.hbm
.xml DB
Create&
setData
Configuration().
configure()
read
openSession
create
main
save(User)
read
INSERT INTO user VALUES(..)
18.
www.SunilOS.com 18
org.hibernate.Session
createQuery– SELECT HQL statement
save() – INSERT Statement
update() – UPDATE Statement
saveOrUpdate()
delete() - DELETE Statement
beginTransaction() – Returns transaction object
createSQLQuery() – Create DB native SQL query
load(dto.class, pk) - Loads record
o Throws exception if record does not exist
get(dto.class, pk) - Get a record
o Returns null in case record does not exist
flush() - synchronize object state with database
www.SunilOS.com 20
org.hibernate.Session
A single-threaded,short-lived object representing a
conversation between the application and the
persistent store.
Wraps a JDBC connection.
Factory for Transaction.
Holds a mandatory (first-level) cache of persistent
objects, used when navigating the object graph or
looking up objects by identifier.
Remove Object from First Level Cache
o session.evict(User)
www.SunilOS.com 22
Hibernate
Hibernate isan object-relational mapping
tool (ORM) that allows for persisting Java
objects in a relational database.
Officially maintained by Jboss, Inc, started in
December, 2001
Opensource (LGPL)
Current Version is 3.2
Will be core of JBoss CMP 2.0 engine
23.
www.SunilOS.com 23
Why Hibernate
Flexibility
Handles all create-read-update-delete (CRUD)
database operations.
(CRUD) operations using simple API; no SQL
Generates DDL scripts to create DB schema (tables,
constraints, sequences)
Flexibility to hand-tune SQL and call stored
procedures to optimize performance
Database Independent
Supports over 20 RDBMS; change the database by
tweaking configuration files
Sits between the database and Java code, easy
database switch without changing any code
24.
www.SunilOS.com 24
Features
Objectoriented query language (HQL)
Portable query language, supports polymorphic queries
etc.
Native SQL
You can also still issue native SQL, and also queries by
“Criteria” (specified using “parse tree” of Java objects)
Transparent persistence
Allows easy saves/delete/retrieve for simple value objects
Very high performance
“In general” due to intelligent (2-level) caching, although in
a few cases hand-written SQL might beat it
Composite Key
APK may consists of multiple
columns Ex. Dept Code +
Employee Code
Multiple properties are maped
for PK
<composite-id> is used in place
of <id>
A separate PK class is created
with composite attributes
PK class must be serializable
and override equals() and
hascode() methods to compare
two primary keys.
www.SunilOS.com 27
28.
www.SunilOS.com 28
Session Factory
SessionFactoryis created using config settings in
hibernate.cfg.xml
Ceate one Session Factory per database
Usually application has single SessionFactory
It is Thread Safe
It is immutable
It is Database Connection Pool
Optionally holds second-level cache
www.SunilOS.com 32
ActionItem
public classAuctionItem{
private long id;
private Set bids;
private String description;
private Bid successfulBid = null;
public Set getBids() {
return bids;
}
public void setBids(Set bids) {
this.bids = bids;
}
…..
}
POJO
JavaBean
Data Transfer
Object (DTO)
BO (Business
Object)
Domain Object
(DO)
33.
www.SunilOS.com 33
Bid
public classBid{
private long id;
private int amount;
private String timestamp;
private long itemId;
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
………
}
Object States
Transient: The instance is not, and has never been associated
with any Session. It has no persistent identity (primary key
value).
Persistent :The instance is currently associated with a Session. It
has a persistent identity (primary key value) and, perhaps, a
corresponding row in the database. For a particular Session,
Hibernate guarantees that persistent identity is equivalent to
Java identity (in-memory location of the object).
Detached :The instance was once associated with a Session, but
that Session was closed, or the instance was serialized to
another process. It has a persistent identity and, perhaps, a
corresponding row in the database.
www.SunilOS.com 43
44.
www.SunilOS.com 44
Optimizing DataAccess
Lazy Fetching ( On Demand )
o Load on demand
o <set name="bids" cascade="all" lazy="true">
Eager (Outer Join) Fetching
o <set name="bids" cascade="all" fetch="join">
o Load entire graph once
o Allows a whole graph of objects connected by many-to-
one, one-to-many, many-to-many and one-to-one
associations to be retrieved in a single SQL SELECT
Batch Fetching
o Hibernate retrieves a batch of entity instances or
collections in a single SELECT, by specifying a list of
primary keys or foreign keys.
45.
www.SunilOS.com 45
Transparent LazyFetching
AuctionItem item = (AuctionItem)
session.get(ActionItem.class, 1);
SELECT … FROM AUCTION_ITEM
WHERE ID = 1
Set bids = item.getBids().;
//Iterator iter = bids.iterate();
SELECT … FROM BID WHERE ITEM_ID
= ?
46.
www.SunilOS.com 46
Transparent EagerFetching
AuctionItem item = (AuctionItem)
session.get(ActionItem.class, 1);
SELECT i.*, b.* FROM AUCTION_ITEM i,
BID b WHERE ITEM_ID = 1 AND
i.ID = b.ITEM_ID
Cascade
<one-to-one name="person" cascade=“all"/>
<one-to-onename="person"
cascade="persist,delete,lock"/>
For each basic operation of the Hibernate session -
including persist(), merge(), saveOrUpdate(),
delete(), lock(), refresh(), evict(), replicate() - there
is a corresponding cascade style. Respectively, the
cascade styles are named create, merge, save-
update, delete, lock, refresh, evict, replicate.
Special value : delete-orphan
www.SunilOS.com 48
49.
Cascade ( Cont.)
delete-orphan : applies only to one-to-many
associations, and indicates that the delete()
operation should be applied to any child
object that is removed from the association.
Cascade is recommended for <one-to-one>
and <one-to-many> but not for <many-to-
one> or <many-to-many> association
www.SunilOS.com 49
50.
www.SunilOS.com 50
HQL
Q– Get all parts
SQL - SELECT * FROM part;
Query query = session.createSQLQuery(“SELECT * FROM part”);
Query query = session.createQuery(“from Part”);
List list = query.list();
Iterator iter = list.iterator();
Part dto;
while (iter.hasNext()) {
dto =(Part)iter.next();
System.out.println(dto.getId() + "t" + dto.getName()+ "tt"
+dto.getColor());
}
51.
www.SunilOS.com 51
HQL -Getall grey parts
SQL - SELECT * FROM part WHERE color like ‘Grey%’;
Query query = session.createQuery(“from Part where color like ‘Grey
%’”);
List list = query.list();
Iterator iter = list.iterator();
Part dto;
while (iter.hasNext()) {
dto =(Part)iter.next();
System.out.println(dto.getId() + "t" + dto.getName()+ "tt"
+dto.getColor());
}
52.
www.SunilOS.com 52
HQL –Get some columns
Q- Get all parts’ ids, names
SELECT id, name FROM part;
Query query = session.createQuery(“select p.id, p.name from Part p”);
List rows = query.list();
Iterator iter = rows.iterator();
Object[] columns;
System.out.println("IDtName");
while (iter.hasNext()) {
o columns = (Object[])iter.next();
o Integer id = (Integer) columns[0];
o String name = (String) columns[1];
o System.out.println(id + "t" + name);
}
53.
www.SunilOS.com 53
HQL-Joins
Q- Getparts with their City of Unit
SELECT part.id, name, color, unit.city
FROM part, unit WHERE unit.id =
part.unit_id;
Query query = session.createQuery(“select
p.id, p.name, p.color, u.city from Part p, Unit
u where p.unitId = u.id”);
54.
www.SunilOS.com 54
HQL –Order By
Q- Get all grey parts sorted by name
SQL – SELECT * FROM part WHERE color
like ‘Grey%’ ORDER BY name;
HQL – from Part where color like ‘Grey%’
order by name
55.
www.SunilOS.com 55
HQL -Aggregate Functions
Q- How many parts are there?
SELECT count(*) from part;
Query query = session.createQuery(“select
count(*) from Part”);
List rows= query.list();
Integer row = (Integer)rows.get(0);
56.
www.SunilOS.com 56
HQL –Group By
Q- Get parts’ color count
SQL – SELECT color,count(*) FROM part
GROUP BY color
Query query = session.createQuery(“select
p.color,count(*) from Part p group by
p.color”);
57.
www.SunilOS.com 57
Criteria
Q –Get all parts
SQL - SELECT * FROM part;
Query query = session.createQuery(“from
Part”);
Criteria crit =
session.createCriteria(Part.class);
List list = crit.list();
58.
www.SunilOS.com 58
Get allgrey parts
SQL - SELECT * FROM part WHERE color
like ‘Grey%’;
Query query = session.createQuery(“from
Part where color like ‘Grey%’”);
Criteria crit =
session.createCriteria(Part.class);
crit.add(Restrictions.like(“color", “Grey%"));
crit.add(Restrictions.eq(“unitId", “2"));
List list = crit.list();
59.
www.SunilOS.com 59
Criteria –selected attributes
Q- Get all parts’ ids, names
SELECT id, name FROM part;
HQL - select p.id, p.name from Part p
Criteria crit = session.createCriteria(Part.class);
ProjectionList p = Projections.projectionList();
p.add(Projections.property("id"));
p.add(Projections.property(“name"));
crit.setProjection(p);
List list = crit.list();
60.
www.SunilOS.com 60
Criteria –Aggregate Functions
Q- How many parts are there?
SELECT count(id) from part;
Query query = session.createQuery(“select count(id) from Part”);
Criteria crit = session.createCriteria(Part.class);
o ProjectionList projList = Projections.projectionList();
o projList.add(Projections.count(“id"));
o projList.add(Projections. rowCount()); //count(*)
o projList.add(Projections.groupProperty(“color")); //Group by
o crit.setProjection(projList);
o List results = crit.list();
Other Aggregate Function
o Projections.max
o Projections.min
o Projections.avg
61.
www.SunilOS.com 61
Criteria –AND Condition
Criteria crit =
session.createCriteria(Part.class);
crit.add(Restrictions.like(“color", “Grey%"));
crit.add(Restrictions.eq(“unitId", “2"));
Default is AND condition
www.SunilOS.com 63
Criteria
Order By
oCriteria crit = session.createCriteria(Part.class);
o crit.add(Restrictions.like(“color", “Grey%"));
o Crit.addOrder( Order.asc(“name") );
o Crit.addOrder( Order.asc(“color") );
o Crit.addOrder( Order.dsc(“id") );
Get Max records
o crit.setMaxResults(10);
Get First few Record
o crit.setFirstResult(11)
Create Aliases
o crit.createAlias(“Part", “p")
64.
www.SunilOS.com 64
Criteria -Join
Applying the restrictions becomes easy in the case of joins
as well. For example, the following query
SELECT O.*, P.* FROM ORDERS O, PRODUCT P
WHERE
O.ORDER_ID=P.ORDER_ID AND P.ID=’1111’;
Would become
List orders = session.createCriteria(Order.class);
orders.setFetchMode(“products”,FetchMode.JOIN);
orders.add(Restrictions.eq(“id”,”1111”));
orders.list();
65.
www.SunilOS.com 65
Criteria –Group By
SELECT COUNT(ID) FROM ORDER HAVING
PRICETOTAL>2000 GROUP BY ID
Can be rewritten in Criteria query as follows:
List orders = session.createCriteria(Order.class)
.setProjection( Projections.projectionList()
.add( Projections.count(“id”) )
.add( Projections.groupProperty(“id”) )
)
.list();
66.
www.SunilOS.com 66
DetachedCriteria
Someapplications need to create criteria queries in
"detached mode", where the Hibernate session is not
available. This class may be instantiated anywhere, and
then a Criteria may be obtained by passing a session to
getExecutableCriteria(). All methods have the same
semantics and behavior as the corresponding methods of
the Criteria interface.
www.SunilOS.com 69
Cache
Cachingis used to optimize database
applications.
A cache reduces traffic between application
and the database by conserving data
already loaded from the database.
The application may need to empty
(invalidate) the cache from time to time if
the database is updated in some way,
because it has no way of knowing whether
the cache is up to date.
70.
Type of Cache
Hibernate has 3 cache Level
o Query Cache
o First Level Cache
o Second Level Cache
www.SunilOS.com 70
71.
www.SunilOS.com 71
Query Cache
Queryresult sets may be cached. It is useful when
same queries are run frequently with the same
parameters.
To use the query cache enable it from
hibernate.cfg.xml by
<property
name="hibernate.cache.use_query_cache">
true </property>
query.list();
query.list(); //Same result will be fetched from Q
Cache
72.
www.SunilOS.com 72
Query Cache( Cont. )
The query cache can be forcefully
refreshed by
query.setCacheMode(CacheMode.REFRESH ).
query.list();
73.
First & SecondLevel Cache
www.SunilOS.com 73
SessionFactory Object
Mandatory
74.
www.SunilOS.com 74
First LevelCache
Associated with Session object.
It is a transaction-level cache of persistent data. It is
used by default.
When an object is pass to save(), update() or
saveOrUpdate() and retrieved by load(), get(), list(),
iterate() or scroll(), that object is added to the
internal cache of the Session.
When flush() is subsequently called, the state of
that object will be synchronized with the database
75.
Remove from 1st
Level
Anobject is removed from first level
cache using evict(dto) method.
Method clear() can be removed all
objects from first level cache.
www.SunilOS.com 75
76.
www.SunilOS.com 76
Second LevelCache
It is an optional cache and Stores objects across
session.
It is configured on a per-class and per-collection
basis. It can cache a class or a collection
An object is always searched in First-Level cache
before locating in Second-Level cache.
77.
www.SunilOS.com 77
Second LevelCache
Use <class-cache> and <collection-cache> elements
in hibernate.cfg.xml.
o <class-cache class="org.dto.Item" usage="read-write"/>
o <class-cache class="org.dto.Bid" usage="read-only"/>
o <collection-cache collection="org.dto.Item.bids"
usage="read-write"/>
78.
Enable Second LevelCache
By default it is disabled , you can enable it in
hibernate.cfg.xml
<property
name="hibernate.cache.use_second_level_cache">
o true
</property>
www.SunilOS.com 78
www.SunilOS.com 89
Join Query
Q: Get all ChequeNumbers
select chq_number from cheque_payment
Q: Get all Cheque Number and their amounts
select chq_number, amount from Payment p,
cheque_payment cp
where p.payment_id = cp.payment_id
select amount from Payment, cheque_payment where
payment.payment_id = cheque_payment.payment_id
select sum(amount) from Payment, cheque_payment where
payment.payment_id = cheque_payment.payment_id
Disclaimer
This is aneducational presentation to enhance the
skill of computer science students.
This presentation is available for free to computer
science students.
Some internet images from different URLs are used
in this presentation to simplify technical examples
and correlate examples with the real world.
We are grateful to owners of these URLs and
pictures.
www.SunilOS.com 101