Hibernate Reference Persistence for Idiomatic Java HIBERNATE
05-Hibernate-Object Lifecycle Persistence and Session Management
-
Upload
hariprasad025 -
Category
Documents
-
view
240 -
download
0
Transcript of 05-Hibernate-Object Lifecycle Persistence and Session Management
-
8/10/2019 05-Hibernate-Object Lifecycle Persistence and Session Management
1/33
2009 coreservlets.com
, ,and Session Management
Originals of Slides and Source Code for Examples:
http://courses.coreservlets.com/Course-Materials/hibernate.html
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
2009 coreservlets.com
For live Spring & Hibernate training, seecourses a p: courses.coreserv e s.com .Taught by the experts that brought you this tutorial.
,can be held on-site at your organization.
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
ourses eve ope an aug y ar y a Java 5, Java 6, intermediate/beginning servlets/JSP, advanced servlets/JSP, Struts, JSF, Ajax, GWT, custom mix of topics
Courses developed and taught by coreservlets.com experts (edited by Marty) Spring, Hibernate/JPA, EJB3, Ruby/Rails
Contact [email protected] for details
-
8/10/2019 05-Hibernate-Object Lifecycle Persistence and Session Management
2/33
Topics in This Section
Learn the lifecycle of Hibernateentities, when they transition fromstatetostate, and how this affectsdevelopment
Take a closer look at persistence, anddiscover how Hibernate manages dirtyand related objects
See how Hibernate uses a Session to
keep track of, and optimize, useractivities
4
Hibernate Object Lifecycle
Hibernate considers objects it canmanage o a ways e n one o ourstates
Persistent
RemovedDetached
Objects transition from state to statethrough various method calls
-
8/10/2019 05-Hibernate-Object Lifecycle Persistence and Session Management
3/33
Transient State
All objects start off in the transients a e
Account account = new Account();
Hibernate is not aware of the object
Not related to database rowNo value for accountId
Garbage collected when no longer
referenced by any other objects
Persistent State
Hibernate is aware of, and managing, the object
as a a a ase
Already existing object retrieved from the database
Formerl transient ob ect about to be saved
This is the only state where objects are saved to thedatabase o ca ons ma e n o er s a es are save o e a a ase w e
the object remains in that state
Changes to objects in a persistent state are automatically saved to the
Objects are made persistent through calls against theHibernate session
session.save(account); session.lock(account);
session.update(account); session.merge(account);
-
8/10/2019 05-Hibernate-Object Lifecycle Persistence and Session Management
4/33
Persistent State
Session session =.
// transient state Hibernate is NOT aware that it existsAccount account = new Account
// transition to the persistent state. Hibernate is NOW// aware of the ob ect and will save it to the databasesession.saveOrUpdate(account);
// modification of the object will automatically be// saved because the object is in the persistent stateaccount.setBalance(500);
// commit the transactionsession.getTransaction().commit();
Removed State
A previously persistent object that isdeleted from the databasesession.delete(account);
Java instance may still exist, but it is
ignored by HibernateAny changes made to the object are not saved to
the database
Picked up for garbage collection once it falls outof scope
erna e oes no nu -ou e n-memoryobject
-
8/10/2019 05-Hibernate-Object Lifecycle Persistence and Session Management
5/33
Removed State
Session session = SessionFactory.getCurrentSession();
// retrieve account with id 1. account is returned in a persistent state
Account account = session.get(Account.class, 1);
.// database record, and no longer manages the objectsession.delete(account);
// modification is ignored by Hibernate since it is in the removed stateaccount.setBalance(500);
// commit the transactionsession.getTransaction().commit();
// notice the Java object is still alive, though deleted from the database. ,account.setBalance(1000);
Detached State
A persistent object that is still referenced
session.close() changes objects state from persisted todetached
Still represents a valid row in the database
No lon er mana ed b HibernateChanges made to detached objects are not saved to the
database while object remains in the detached state
an e rea ac e , re urn ng o e pers s en s a e ancausing it to save its state to the database
update();
merge();
lock(); // reattaches, but does not save state
-
8/10/2019 05-Hibernate-Object Lifecycle Persistence and Session Management
6/33
Detached State
Session session1 = SessionFactory.getCurrentSession();
// retrieve account with id 1. account is returned in a persistent stateAccount account = session1.get(Account.class, 1);
// transition to the detached state. Hibernate no longer manages the objectsession1.close();
// modification is ignored by Hibernate since it is in the detached// state, but the account still represents a row in the databaseaccoun .se a ance ;
// re-attach the object to an open session, returning it to the persistent// state and allowing its changes to be saved to the database
.
session2.update(account);
// commit the transaction. .
Hibernate Lifecycleif not
persisted
Removednew
save()
saveOrUpdate()
persist()
merge()
delete()
remove()
upon
session
closure
Persistent
get()
load()
find()
evict()
clear()
update()
saveOrUpdate()
merge()
Detached Garbageif not reattached
-
8/10/2019 05-Hibernate-Object Lifecycle Persistence and Session Management
7/33
Saving Changes to the Database
Session methods do NOT save changes to
save();u date ;
delete();
These methods actually SCHEDULE
Hibernate collects SQL statements to beissued
Statements are later flushed to the database
Once submitted, modifications to the database are not
session.getTransaction().commit();
The Persistence Context
Managed object environment o or concre e o ec o re erence, us concep ua
Thought of as containing:
Graph of managed persistent instances
Each Hibernate session is said to have one
persistence context
G
INSERT
UPDATE Ls
B D E
DELETE
INSERT
UPDATE istofS
Statement
Hibernate
Session
Map of Objects
PERSISTENCE CONTEXT
-
8/10/2019 05-Hibernate-Object Lifecycle Persistence and Session Management
8/33
Flushing the Context
Submits the stored SQL statements toe a a ase
Occurs when: transaction.commit() is called
session.flush() is called explicitly
If stored statements would affect the results of the query
Flush modes session.setFlushMode()
FlushMode.AUTO: Default. Called as described above FlushMode.COMMIT: Not flushed before queries
FlushMode.MANUAL: Only when explicit flush() is called
Hibernate Session
Single threaded nonshared objectthat represents a unit of work
Used to retrieve objects from thedatabase
Contains the ersistence context
in the database
-
8/10/2019 05-Hibernate-Object Lifecycle Persistence and Session Management
9/33
Session API
session.save(Object o)Schedules insert statements to create the new
object in the database
session.update(Object o)Schedules update statements to modify the
existing object in the database
Scheduled ChangesSession session = SessionFactory.getCurrentSession();
// transient state Hibernate is NOT aware that it exists
Account account = new Account();
.
// aware of the object and will save it to the database
// schedules the insert statements to create the object in the database
session.saveOrUpdate(account);
// modification of the object will automatically be
// saved scheduled because the object is in the persistent state
// (actually alters the initial insert statement since it hasnt been sent yet)
account.setBalance(500);
session.getTransaction().commit();
-
8/10/2019 05-Hibernate-Object Lifecycle Persistence and Session Management
10/33
Session API
session.saveOrUpdate(Object o)Convenience method to determine if a save or
update is required
session.merge(Object o)Retrieves a fresh version of the object from the
database and based on that, as well asmo ca ons ma e o e o ec e ng passe n,schedules update statements to modify the
.
Session API
session.get(Object.class, Identifier)Retrieves an object instance, or null if not found
sess on. oa ec .c ass, en er Retrieves an object instance but does NOT result in a
a a ase ca If managed instance not found, will return a proxy
Ob ect full initialized when non-id attribute is accessed
If detached, throws ObjectNotFoundException
-
8/10/2019 05-Hibernate-Object Lifecycle Persistence and Session Management
11/33
Session API
session.lock(Object, LockMode)Reattaches a detached object to a session without
scheduling an update
sess on.re res ecGets the latest version from the database
Session API
session.delete(Object)Schedule an object for removal from the database
session.evict(Object)
Removes individual instances from persistencecontext, changing their state from persistent todetached
-
8/10/2019 05-Hibernate-Object Lifecycle Persistence and Session Management
12/33
Session API
session.clear() emoves a o ects rom pers stence context, c ang ng a
their states from persistent to detached
session.replicate(Object, ReplicationMode) Used for persisting records across databases
ReplicationModes EXCEPTION: throw exception if row exists
LATEST_VERSION: choose the latest version to save
OVERWRITE: overwrite existing row
2009 coreservlets.com
asca ng
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
-
8/10/2019 05-Hibernate-Object Lifecycle Persistence and Session Management
13/33
Cascading Object Persistence
Hibernate represents domain objectrelationships through a graph model
B D E
ropaga e e pers s ence ac on no on y o
the objectsubmitted
, but also to any objects
Cascade Attribute
none e au t e av or
save-update Associated objects can be transient or detached
deleteDeletes associated persistent instances delete-orphan
removed from a collection
Enabling this tells Hibernate that the associated class is,
removed from its associated collection
-
8/10/2019 05-Hibernate-Object Lifecycle Persistence and Session Management
14/33
Save-or-Update: Non-Cascade
Previously, to add relationships to new
A C F G
B D EH
I
J
session.saveOrUpdate(H); ma e pers stentsession.saveOrUpdate(I); // make I persistent
session.saveOrUpdate(J); // make J persistentC.add(H); // add relationshi with HC.add(I); // add relationship with IC.add(J); // add relationship with Jsession.saveOrUpdate(C); // save relationships through C
Cascade="save-update"
< name="accountI " co umn="ACCOUNT_ID">
" " - " "_
c ass
-
8/10/2019 05-Hibernate-Object Lifecycle Persistence and Session Management
15/33
Save-or-Update: Cascade
With cascade, no need to persist the.
persist them automatically
A C F G
B D EH
J
C.add(H); // add relationship with H
I
C.a I ; a re a ons p wC.add(J); // add relationship with Jsession.saveOrUpdate(C); // save relationships through C
Save-or-Update: Non-Cascade
Previously, if several associated objectswere modified
A C F G
B D E
session.saveOrUpdate(C);
session.saveOrUpdate(D);
session.saveOrUpdate(E);
session.saveOrUpdate(F);
-
8/10/2019 05-Hibernate-Object Lifecycle Persistence and Session Management
16/33
Save-or-Update: Cascade
Now, call one and let Hibernatecascade the action across associatedobjects
A C F G
B D E
session.saveOrUpdate(C);
Delete: Non-Cascade
Before, deleting an object and itsdependants required several calls
A C F G
B D E
session.delete(C);
session.delete(D);
session.delete(E);
session.delete(F);
-
8/10/2019 05-Hibernate-Object Lifecycle Persistence and Session Management
17/33
Cascade="delete"
one- o-many c ass= er
Delete: Cascade
Now, deleting an object and all of itsdependants is much easier
A C F G
B D E
session.delete(C);
-
8/10/2019 05-Hibernate-Object Lifecycle Persistence and Session Management
18/33
Cascade="delete-orphan"
" " " " _
=" " =" " _
type="timestamp" update="false" />
-
8/10/2019 05-Hibernate-Object Lifecycle Persistence and Session Management
19/33
Other Cascade Settings
lockReattaches detached associated objects
re licateReplicates associated objects
evictEvicts associated objects from the persistence
context
all
Cascades ever thin but delete-or han Can still include by setting cascade="all, delete-orphan"
Cascading Delete for M:M
Issue using M:M and setting cascade delete De ete Jac , tr es to e ete Account 1, w c J st s a assoc ate
with results in an error (if using database constraints)
2
1
OWNER_ID
JILL
JACK
NAME
OWNER_ID ACCOUNT_ID
2
1
ACCOUNT_ID
500
100
BALANCE
Hibernate discourages it
2 1
Recommends NOT using cascade on M:M
You should be using 1:M
M:M anyway!
-
8/10/2019 05-Hibernate-Object Lifecycle Persistence and Session Management
20/33
Cascading Delete for M:M
Recommended way to handle this is to use two- -
No tag
Cascade on the When Jack ets deleted:
Jacks record is deleted from the OWNER table The relationship for his account is deleted from the join table Use a database trigger on the join table to check for other existing
owners o e same accoun , an none, e e e e accounfrom the account table
2
1
OWNER_ID
JILL
JACK
NAME
2
1
ACCOUNT_ID
500
100
BALANCE
2
1
_
1
1
_
2009 coreservlets.com
ess on anagemen
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
-
8/10/2019 05-Hibernate-Object Lifecycle Persistence and Session Management
21/33
Hibernate Architecture High
*Source: Official Hibernate Documentation
Hibernate Arch Lite
The Lite" architecture has the application provide its
transactions
*Source: Official Hibernate Documentation
-
8/10/2019 05-Hibernate-Object Lifecycle Persistence and Session Management
22/33
Hibernate Arch Full Cream
The "full cream" architecture abstracts the application
API (JTA) and lets Hibernate take care of the details
*Source: Official Hibernate Documentation
Obtaining the Session
SessionFactory.getCurrentSession() euses an ex s ng sess on
If none exists, creates one and stores it for future use
Automaticall flushed and closed whentransaction.commit() is executed
FlushMode.AUTO SessionFactory.openSession()
Always obtains a brand new session
Provides/requires more management FlushMode.MANUAL
http://www.hibernate.org/42.html
-
8/10/2019 05-Hibernate-Object Lifecycle Persistence and Session Management
23/33
Obtaining the Session
Within JavaSE environment, currentsessions are saved on the threadhibernate.cfg.xml
= _ _ _
thread
rea oca ess on a ernUse ThreadLocal variable to maintain session data
rea oca
Specialized Java class which is associated to a users
throughout the lifespan of the thread (or child threads)
Obtaining the Session
Within a container, managed as part ofthe JTA implementationhibernate.cfg.xml
jta
Session is scoped and bound to theJTA Transaction
More about this when we talk aboutTransactions.
-
8/10/2019 05-Hibernate-Object Lifecycle Persistence and Session Management
24/33
Conversation
Unit of work that spans multiple requests xamp e:
User enters a form that spans several screens New Bank Account Creation
Page 1 Request 1Create Account Object
Page 2 Request 2Collect user information, save account to database
Collect information for a single EBiller, build an EBiller
object, and associate it to the account, save to database
Page 4 Request N+1Display saved information summary
Conversations in Hibernate
Unit of work that spans multiple HibernateSessions (think multiple requests)
Each request starts and ends its own
Possibly modifies persistent objects
Mi ht want to ersist to the database at a later oint intime (i.e. subsequent request when in possession ofmore information)
Use detached objects
Session-per-request with detached objects
Use an extended Persistence Context
Session-per-conversation
-
8/10/2019 05-Hibernate-Object Lifecycle Persistence and Session Management
25/33
Session-per-request with
Previously persisted objects thatcontinue to represent rows of data inthe database that are available to bemodified outside of the HibernateSession
After changes are complete, thesedetached objects are reattached via
an update, merge, or lock
Session-per-request with
Page 1 Request 1
Account is transient
Page 2 Request 2 Collect user information, save account to database
Account transitions to persistent, but we still want thataccount object available when we get to page 3, so wedetach it from the Hibernate session
Collect information for a single EBiller, build an EBiller object, and
associate it to my account, save to database EBiller starts off transient, transitions to persistent for the
,for later pages
Also reattaching the Account object to save the relationship,and then detaching that again as well.
Page 4 Request N+1 Display saved information summary using detached objects
-
8/10/2019 05-Hibernate-Object Lifecycle Persistence and Session Management
26/33
Using Session-per-request with
1. Create transient objects as needed.
3. Modify/obtain objects from the database through the sessio
as needed These object will then be in the persistent state and associated to the
persistence context
4. Close the session This will change the state of these objects to detached
e care u anges o o ec s n a pers s en s a e w e save othe database when closing the session!
5. Modify detached objects outside of the session as needed.
needed across multiple requests
7. When the unit-of-work is complete, get a handle to thecurrent session (if not already obtained)8. Reattach the objects to be persisted
Through an update(), merge() or lock() call
Reattach using update()
Need to reattach the ob ect to thepersistence context
update SQL command, which
call erna e oesn now w a , any ng,
changed while it was outside
Not arm u , ut cou e unnecessary
-
8/10/2019 05-Hibernate-Object Lifecycle Persistence and Session Management
27/33
Detached Object - Update Example
public void testUpdateAccountBalance() {
// Get a handle to the current Session
Session session =
HibernateUtil.getSessionFactory().getCurrentSession();session.beginTransaction();
// Modify objects
Account account = new Account();
.
// Close the Session without modifying the persistent object
// Changes the state of the objects to detached
session.getTransaction().commit();
HibernateUtil.getSessionFactory().close();
o y e ac e o ec ou s e o sess on
account.setBalance(2000);
...
Detached Object - Update Example
...
// Get an e to a su sequent Sess on
Session session2 =
HibernateUtil.getSessionFactory().getCurrentSession();
session2.beginTransaction();
// Reattach the object to be persisted.
// An update statement will be scheduled regardless
// of whether or not object was actually updated
.
// Commits/closes the session
// Saves the changes made in the detached state
session2. etTransaction .commit
-
8/10/2019 05-Hibernate-Object Lifecycle Persistence and Session Management
28/33
Reattach using lock()
Reattaches the ob ect without
forcing an update place
persisted
state is changed from detached to
Reattach using merge()
Does NOT reattach the object passed in Checks to see if the object already exists in
the system ,Creates a new instance otherwise
Copies the values of the submitted objectinto the persistent object from previous step Returns a reference to the final merged
Note: SUBMITTED OBJECT STATE DOESNOT CHANGEMerging does not affect the submitted item reference. It
is up to the developer to replace it if they so desire
-
8/10/2019 05-Hibernate-Object Lifecycle Persistence and Session Management
29/33
Detached Object - Merge Example
...
// Get a handle a subsequent Session
Session session2 =
HibernateUtil.getSessionFactory().getCurrentSession();
session2.be inTransaction
// Reattach the object using merge.
// The data is persisted, but the passed in
session2.merge(account);
// Since this account object is NOT
// pers stent, change s not saved
account.setBalance(100);
// Commits/closes session
// Saves the changes made in the detached state
session2.getTransaction().commit();
Detached Object - Merge Example
...
// Get a an e a su sequent Sess on
Session session2 =
HibernateUtil.getSessionFactory().getCurrentSession();
session2.beginTransaction();
// Correct use of the merge operation.
// Now, my account reference is pointing
// to the updated object in memory
.
// Change is NOW saved
account.setBalance(100);
// Commits/closes session
// Saves the changes made in the detached state
session2.getTransaction().commit();
-
8/10/2019 05-Hibernate-Object Lifecycle Persistence and Session Management
30/33
Reattach using delete()
Used to remove detached objectsdirectly from the database
Though invisible to the user, delete()will first reattach the ob ect via aproxy, and then scheduled it fordeletion just like a normal delete
Session-per-Conversation
Extendin the ersistence contextKeep the same persistence context across server
requests
Reconnected upon subsequent requests
No more detached objectsAll objects are either transient or persistent
No need for reattaching/merging
Synchronized with database at end ofthe conversation
-
8/10/2019 05-Hibernate-Object Lifecycle Persistence and Session Management
31/33
Session-per-Conversation
Session is disconnected from the underlying JDBC
Persistence context is held on in some persistent state
HTTPSession
Persistence context is reconnected when thesession begins the next transaction
ec s oa e ur ng e conversa on are n e pers s en s a e;never detached
All changes are synchronized with the db when flush() is called
Set FlushMode.MANUAL when the conversation begins and the
Session is opened database session.flush() at the end of the conversation
Session-per-Conversation
Still trying to gain traction Implemented by the JBoss Seam
application framework ons ere o e comp ca e y many
developers
Need to write an interceptor to bind and unbindthe Session at the be innin and end of eachrequest
Need to figure out if the conversation is complete
Refer to documentation for details
-
8/10/2019 05-Hibernate-Object Lifecycle Persistence and Session Management
32/33
2009 coreservlets.com
rap-up
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Summary
In this lecture, we: ,
objects state affects its persistence behavior Transient not persisted Detached previously managed by Hibernate and
requires re-attachment
Learned how to cascade object activities cascade="delete " | cascade="delete-orphan"
Took a closer look at the Session object, explored the concept of thePersistence Context and discovered many different persistentmec an sms
flush(), merge(), persist(), lock() etc... Defined conversation and the ways to implement them and carry
Session-per-request with detached objects Session-per-conversation
-
8/10/2019 05-Hibernate-Object Lifecycle Persistence and Session Management
33/33
Preview of Next Sections
Transaction management
Automatic versioning of objects
66
2009 coreservlets.com
ues ons