Wednesday, December 23, 2015

Hibernate Session

Hibernate Session Definition: 


An instance which represents a set of operations(crud) on database
A persist related interface


factory.openSession VS factory.getCurrentSession




factory.openSessionfactory.getCurrentSession
ThreadNot relatedUsing ThreadLocal, bind to current thread
When closerequire manual closeauto close after commit or rollback
When to useno thread relatedwant operation in same thread
Transactionnot requiredrequire transaction commit
Confignot required<property name="hibernate.current_session_context_class"> thread</property>


Session Range
<property name="hibernate.current_session_context_class"> thread</property>

hibernate.current_session_context_class: jta, thread, managed, custom.Class
jta: cross databases/hosts, remote server database
thread: local events only, for one single database


Session states: (to be introduced...)

Transient
Persistent
Detached


Functions


save
merge
persist
saveOrUpdate
lock


get
load


update



delete





session.get VS session.load




Session.getSession.load
Return ObjectReturn target objectReturn a proxy of object
If result not foundReturn nullThrow ObjectNotFoundException
When to useIf the result may be nullIf the result is sure not be null
Cache looking sequenceSession cache(1st level)
2nd level cache
SQL
return
Session cache(1st level)
2nd level cache
return object proxy(lazy)
when use object during session: SQL & return
when use object out of session: throw Exception




Session.load is using Lazy fetching mode, if hbm configures lazy to false, session.load will be the same as session.get

2nd level cache needs configuration to enable

If the same result has been checked more frequently, hibernate will move cache from 2nd level to session cache(1st level)

To cancel Lazy fetching mode, config *.hmb.xml, set <class> tag: lazy="false"






No comments:

Post a Comment