Hibernate Session Definition:
An instance which represents a set of operations(crud) on database
A persist related interface
factory.openSession VS factory.getCurrentSession
factory.openSession | factory.getCurrentSession | |
Thread | Not related | Using ThreadLocal, bind to current thread |
When close | require manual close | auto close after commit or rollback |
When to use | no thread related | want operation in same thread |
Transaction | not required | require transaction commit |
Config | not 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
thread: local events only, for one single database
Transient
Persistent
Detached
Functions
save
merge
persist
saveOrUpdate
lock
get
load
update
delete
save
merge
persist
saveOrUpdate
lock
get
load
update
delete
session.get VS session.load
Session.get | Session.load | |
Return Object | Return target object | Return a proxy of object |
If result not found | Return null | Throw ObjectNotFoundException |
When to use | If the result may be null | If the result is sure not be null |
Cache looking sequence | Session 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"
To cancel Lazy fetching mode, config *.hmb.xml, set <class> tag: lazy="false"