spring管理hibernate session的问题探究
我们再用spring管理hibernate的时候, 我们会继承HibernateDaoSupport 或者HibernateTemplate类.
我们不知道这两个类之间有什么关系. 也没有去关闭session. 让我很是心不安,他可没有关闭session呀.如果..真的是后果不堪设想.百度了好久, 谷歌了好多. 都没有一个像样的说法. 说spring中HibernateDaoSupport会自己关闭session.
眼见为实.于是乎决定查看spring源码一探究竟.
先打开HibernateDaoSupoprt看看.
- public abstract class HibernateDaoSupport extends DaoSupport {
- private HibernateTemplate hibernateTemplate;
- public final void setSessionFactory(SessionFactory sessionFactory) {
- this.hibernateTemplate = createHibernateTemplate(sessionFactory);
- }
- protected HibernateTemplate createHibernateTemplate(SessionFactory sessionFactory) {
- return new HibernateTemplate(sessionFactory);
- }
- public final SessionFactory getSessionFactory() {
- return (this.hibernateTemplate != null ? this.hibernateTemplate.getSessionFactory() : null);
- }
- public final void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
- this.hibernateTemplate = hibernateTemplate;
- }
- public final HibernateTemplate getHibernateTemplate() {
- return hibernateTemplate;
- }
- protected final void checkDaoConfig() {
- if (this.hibernateTemplate == null) {
- throw new IllegalArgumentException("sessionFactory or hibernateTemplate is required");
- }
- }
- protected final Session getSession()
- throws DataAccessResourceFailureException, IllegalStateException {
- return getSession(this.hibernateTemplate.isAllowCreate());
- }
- protected final Session getSession(boolean allowCreate)
- throws DataAccessResourceFailureException, IllegalStateException {
- return (!allowCreate ?
- SessionFactoryUtils.getSession(getSessionFactory(), false) :
- SessionFactoryUtils.getSession(
- getSessionFactory(),
- this.hibernateTemplate.getEntityInterceptor(),
- this.hibernateTemplate.getJdbcExceptionTranslator()));
- }
- protected final DataAccessException convertHibernateAccessException(HibernateException ex) {
- return this.hibernateTemplate.convertHibernateAccessException(ex);
- }
- protected final void releaseSession(Session session) {
- SessionFactoryUtils.releaseSession(session, getSessionFactory());
- }
在这里我们会注意到一个private 对象. 那就是HibernateTemplate. 这里面也有一个HibernateTemplate的set. get.
哦: 原来如此.呵呵,很白痴的事.
比如说. BaseDao extends HibernateDaoSupport 我们会super.getHibernateTemplate.find(hql);
super.getHibernateTemplate.save(obj);
和BaseDao extends HibernateTemplate 中super.find(hql)和super.save(obj);是等效的.
原来没有思考害的我改了一个多小时. 汗..
下面我们来看看HibernateTemplate是怎么样来操作session的呢.
照样我们贴出源代码. 由于这个类代码较多. 我只贴出来几个代表性的属性和方法, 供大家参考.
public class HibernateTemplate extends HibernateAccessor implements HibernateOperations {
private boolean allowCreate = true;
private boolean alwaysUseNewSession = false;
private boolean exposeNativeSession = false;
private boolean checkWriteOperations = true;
private boolean cacheQueries = false;
private String queryCacheRegion;
private int fetchSize = 0;
private int maxResults = 0;
public void ......();
} 一系列的方法.
下面我们看看save()方法.
- public Serializable save(final Object entity) throws DataAccessException {
- return (Serializable) execute(new HibernateCallback() {
- public Object doInHibernate(Session session) throws HibernateException {
- checkWriteOperationAllowed(session);
- return session.save(entity);
- }
- }, true);
- }
我们再看看update(), merge(), find()等方法的源码.
- //update 方法
- public void update(Object entity) throws DataAccessException {
- update(entity, null);
- }
- public void update(final Object entity, final LockMode lockMode) throws DataAccessException {
- execute(new HibernateCallback() {
- public Object doInHibernate(Session session) throws HibernateException {
- checkWriteOperationAllowed(session);
- session.update(entity);
- if (lockMode != null) {
- session.lock(entity, lockMode);
- }
- return null;
- }
- }, true);
- }
- //merge()
- public Object merge(final Object entity) throws DataAccessException {
- return execute(new HibernateCallback() {
- public Object doInHibernate(Session session) throws HibernateException {
- checkWriteOperationAllowed(session);
- return session.merge(entity);
- }
- }, true);
- }
- //find()
- public List find(String queryString) throws DataAccessException {
- return find(queryString, (Object[]) null);
- }
- public List find(String queryString, Object value) throws DataAccessException {
- return find(queryString, new Object[] {value});
- }
- public List find(final String queryString, final Object[] values) throws DataAccessException {
- return (List) execute(new HibernateCallback() {
- public Object doInHibernate(Session session) throws HibernateException {
- Query queryObject = session.createQuery(queryString);
- prepareQuery(queryObject);
- if (values != null) {
- for (int i = 0; i < values.length; i++) {
- queryObject.setParameter(i, values[i]);
- }
- }
- return queryObject.list();
- }
- }, true);
- }
细心的朋友们可能发现了. 他们无一例外的都调用了一个叫做execute()的方法. 对了. 我们再看看execute的面目.到底他干了一件什么样的事情呢?]
- public Object execute(HibernateCallback action, boolean exposeNativeSession) throws DataAccessException {
- Session session = getSession();
- boolean existingTransaction = SessionFactoryUtils.isSessionTransactional(session, getSessionFactory());
- if (existingTransaction) {
- logger.debug("Found thread-bound Session for HibernateTemplate");
- }
- FlushMode previousFlushMode = null;
- try {
- previousFlushMode = applyFlushMode(session, existingTransaction);
- enableFilters(session);
- Session sessionToExpose = (exposeNativeSession ? session : createSessionProxy(session));
- Object result = action.doInHibernate(sessionToExpose);
- flushIfNecessary(session, existingTransaction);
- return result;
- }
- catch (HibernateException ex) {
- throw convertHibernateAccessException(ex);
- }
- catch (SQLException ex) {
- throw convertJdbcAccessException(ex);
- }
- catch (RuntimeException ex) {
- // Callback code threw application exception...
- throw ex;
- }
- finally {
- if (existingTransaction) {
- logger.debug("Not closing pre-bound Hibernate Session after HibernateTemplate");
- disableFilters(session);
- if (previousFlushMode != null) {
- session.setFlushMode(previousFlushMode);
- }
- }
- else {
- SessionFactoryUtils.releaseSession(session, getSessionFactory());
- }
- }
- }
抛掉其他的不管. finally中我们可以看到. 如果existingTransaction 他会
logger.debug("Not closing pre-bound Hibernate Session after HibernateTemplate");
disableFilters(session);
if (previousFlushMode != null) {
session.setFlushMode(previousFlushMode);
}
他并没有立即关闭session.
否则
SessionFactoryUtils.releaseSession(session, getSessionFactory());
他释放掉了session . 真的close()了吗?
我们在看看sessionFactoryUtil.的releaseSession()
- public static void releaseSession(Session session, SessionFactory sessionFactory) {
- if (session == null) {
- return;
- }
- // Only close non-transactional Sessions.
- if (!isSessionTransactional(session, sessionFactory)) {
- closeSessionOrRegisterDeferredClose(session, sessionFactory);
- }
- }
- static void closeSessionOrRegisterDeferredClose(Session session, SessionFactory sessionFactory) {
- Map holderMap = (Map) deferredCloseHolder.get();
- if (holderMap != null && sessionFactory != null && holderMap.containsKey(sessionFactory)) {
- logger.debug("Registering Hibernate Session for deferred close");
- Set sessions = (Set) holderMap.get(sessionFactory);
- sessions.add(session);
- if (!session.isConnected()) {
- // We're running against Hibernate 3.1 RC1, where Hibernate will
- // automatically disconnect the Session after a transaction.
- // We'll reconnect it here, as the Session is likely gonna be
- // used for lazy loading during an "open session in view" pase.
- session.reconnect();
- }
- }
- else {
- doClose(session);
- }
- }
- private static void doClose(Session session) {
- if (session != null) {
- logger.debug("Closing Hibernate Session");
- try {
- session.close();
- }
- catch (HibernateException ex) {
- logger.error("Could not close Hibernate Session", ex);
- }
- catch (RuntimeException ex) {
- logger.error("Unexpected exception on closing Hibernate Session", ex);
- }
- }
- }
spring管理hibernate session的问题探究的更多相关文章
- Spring管理Hibernate
为什么要用Hibernate框架? 既然用Hibernate框架访问管理持久层,那为何又提到用Spring来管理以及整合Hibernate呢? 首先我们来看一下Hibernate进行操作的步骤.比如添 ...
- ssh整合hibernate 使用spring管理hibernate二级缓存,配置hibernate4.0以上二级缓存
ssh整合hibernate 使用spring管理hibernate二级缓存,配置hibernate4.0以上二级缓存 hibernate : Hibernate是一个持久层框架,经常访问物理数据库 ...
- spring管理hibernate,mybatis,一级缓存失效原因
mybatis缓存:一级缓存和二级缓存 hibernate缓存:一级缓存和二级缓存 关于缓存: 缓存是介于物理数据源与应用程序之间,是对数据库中的数据复制一份临时放在内存中的容器, 其作用是为了减少应 ...
- Spring管理Hibernate事务
在没有加入Spring来管理Hibernate事务之前,Hibernate对事务的管理的顺序是: 开始事务 提交事务 关闭事务 这样做的原因是Hibernate对事务默认是手动提交,如果不想手动提交, ...
- Spring管理 hibernate 事务配置的五种方式
Spring配置文件中关于事务配置总是由三个组成部分,DataSource.TransactionManager和代理机制这三部分,无论是那种配置方法,一般变化的只是代理机制这块! 首先我创建了两个类 ...
- [转]利于ThreadLocal管理Hibernate Session
摘自http://aladdin.iteye.com/blog/40986 在利用Hibernate开发DAO模块时,我们和Session打的交道最多,所以如何合理的管理Session,避免Sessi ...
- Spring异常解决 java.lang.NullPointerException,配置spring管理hibernate时出错
@Repository public class SysUerCDAO { @Autowired private Hibernate_Credit hibernate_credit; /** * 根据 ...
- 关于spring管理hibernate事物
下面这篇文章对我帮助很大.http://blog.csdn.net/jianxin1009/article/details/9202907
- Spring对hibernate的事物管理
把Hibernate用到的数据源Datasource,Hibernate的SessionFactory实例,事务管理器HibernateTransactionManager,都交给Spring管理.一 ...
随机推荐
- linux进程的几个状态
[linux进程的几个状态] 1. Linux进程状态:R (TASK_RUNNING),可执行状态&运行状态(在run_queue队列里的状态) 2. Linux进程状态:S (TASK_I ...
- Socket、RPC通信实例,简单版本,仅供查阅
TCP/IP Socket 如果使用TCP协议来传递数据,客户端和服务器端需要分别经过以下步骤: server: 创建socket对象 - bind(绑定socket到指定地址和端口) - liste ...
- python多线程编程5: 条件变量同步-乾颐堂
互斥锁是最简单的线程同步机制,Python提供的Condition对象提供了对复杂线程同步问题的支持.Condition被称为条件变量,除了提供与Lock类似的acquire和release方法外,还 ...
- Laravel 5 项目部署到生产环境的实践
作者:mrcn链接:https://www.zhihu.com/question/35537084/answer/181734431来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请 ...
- [Selenium]Release in dragAndDrop doesn't work after i update the version of Selenium to 2.45.0
在升级Selenium的版本之前,写了一段拖拽的代码,Drag and Drop 都好使的, 但是,将Selenium的版本升级到2.45.0之后,图标拖拽可以成功,释放不生效. 试了N多种解决方案都 ...
- wcf已知类型 known type
.服务契约的定义 /* Copyright (c) 2014 HaiHui Software Co., Ltd. All rights reserved * * Create by huanglc@h ...
- 修改RocketMQ的NameServer端口
---问题--- 有同事提出各个问题:如何修改RocketMQ的NameServer端口号?(默认:9876) ---结论--- 调查并验证之后,结论及过程如下: 验证版本:rocketmq-all- ...
- Executing a Finite-Length Task in the Background
[Executing a Finite-Length Task in the Background] Apps that are transitioning to the background can ...
- jquery怎么根据后台传过来的值动态设置下拉框、单选框选中
$(function(){ var sex=$("#sex").val(); var marriageStatus=$("#marriageStatus").v ...
- 日志文件(关于#IRSA_MDPS_RDM软件 密码登录事项 7月26号)
1.登录:sqlplus 用户名:scott 口令:123 qweas.. //2018-7-16号更改密码 2.查看该用户(已登录)下有几个表:select table_name from user ...