getHibernateTemplate().getSessionFactory().getCurrentSession()的意思是得到当前线程 绑定的session,而当前线程绑定的session是通过当前的事务产生的,如果你没有配置事务的话,当前线程threadlocal中就不存在 session,这样就出现no session错误。
而execute的回调方法,看源码HibernateTemplate中写道
public Object execute(HibernateCallback action, boolean exposeNativeSession)
throws DataAccessException {
Assert.notNull(action, "Callback object must not be null");
Session session = getSession();
boolean existingTransaction = (!isAlwaysUseNewSession() && (!isAllowCreate() || SessionFactoryUtils
.isSessionTransactional(session, getSessionFactory())));
}
protected Session getSession() {
if (isAlwaysUseNewSession()) {
return SessionFactoryUtils.getNewSession(getSessionFactory(),
getEntityInterceptor());
} else if (isAllowCreate()) {
return SessionFactoryUtils.getSession(getSessionFactory(),
getEntityInterceptor(), getJdbcExceptionTranslator());
} else {
try {
return getSessionFactory().getCurrentSession();
} catch (HibernateException ex) {
throw new DataAccessResourceFailureException(
"Could not obtain current Hibernate Session", ex);
}
}
}
其中默认private boolean alwaysUseNewSession = false,所以代码会走到else if (isAllowCreate())
注意这里:else if (isAllowCreate()),其中在HibernateTemplate类中默认private boolean allowCreate = true;
意思说如果当前线程中的session不存在的话,是否允许创建,而默认是允许的,通过函数名字就很清楚,接下来是创建当前线程中的session的代码,所以在没有事务的状态下,用execute回调方法,就不会出现上述问题。
分享到:
相关推荐
No Hibernate Session bound to thread,没有绑定线程解决办法,找了好久才找到的
Hibernate-nosession浅谈代码案例。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
hibernate就会抛出: No Hibernate Session bound to thread, and configuration does not allow creation of one here}异常。 在实际的SSH web应用开发中,我们通常用spring来进行事务的管理。我们一般不会在dao层...
在spring+hibernate的框架中定时操作数据库,主要是拿到sessionFactory,不会出现no session 和transaction no-bound等问题,由sessionFactory完成对数据的操作,有些包是没有用的,有兴趣的可以自己删除掉
1. Introduction to Hibernate 1.1. Preface 1.2. Part 1 - The first Hibernate Application 1.2.1. The first class 1.2.2. The mapping file 1.2.3. Hibernate configuration 1.2.4. Building with Ant 1.2.5. ...
发现在客户的某个PHP版本下,执行某类操作的时候,总是会报如下错误 Invalid parameter number: no parameters were bound,经google,发现是php版本过低导致
配置tomcat7sqlserver数据连接池java 利用数据源对象建立数据库连接时的错误: Name jdbc is not bound in this Context 解决方案
Name salesDataSource is not bound in this Context,连接池的问题
On a search problem related to branch-and-bound procedures.pdfOn a search problem related to branch-and-bound procedures.pdfOn a search problem related to branch-and-bound procedures.pdfOn a search ...
Android Service之bound实现
branch and bound
ADO Data Bound Class WizardADO数据类向导
lower_bound函数lower_bound函数用法及应用领域和案例分享lower_bound函数用法及应用领域和案例分享lower_bound函数用法及应用领域和案例分享lower_bound函数用法及应用领域和案例分享lower_bound函数用法及应用领域...
upper confidence bound implementation
错误信息: XXXX client has already been bound to another coroutine使用协程客户端时出现以下错误信息:re
本案例主要是分别实现Spring与jdbc和hibernate结合的事务控制,如果该案例有出入的地方,请给我留言,我们一起交流
本推理系统可用于命题、谓词、注解命题和注解谓词的自动推理,系统自动识别是何种类型推理。 <br>注解命题和注解谓词的推理可以解决一般的推理中的不协调问题(即系统中存在矛盾)。
NULL 博文链接:https://samson7b.iteye.com/blog/1393458
usb分析软件,可以查看系统里的usb设备,并有具体分析