public String dynamicSouce(){
DynamicDataSource.setCustomerType(DynamicDataSource.DATA_SOURCE_2);
Session session = sessionFactory.openSession();
//Session session = sessionFactory.getCurrentSession();
BigInteger count = (BigInteger) session.createSQLQuery("select count(*) from videoinfo").uniqueResult();
System.out.println(count);
return "result";
}
以上代码运行正常
但是openSession()换成getCurrentSession()后报错:HibernateException: No Session found for current thread
解决:applicationContext.xml配置文件已经配置了sessionFactory,为什么找不到呢
在web.xml配置文件中加入对OpenSessionInViewFilter的配置
<!-- openSessionInView配置 -->
<filter>
<filter-name>openSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openSessionInViewFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
接下来又
报错:*** is not valid without active transaction
手动添加beginTransaction()和.commit()后运行正常,说明spring没有自动开启transaction
public String dynamicSouce(){
DynamicDataSource.setCustomerType(DynamicDataSource.DATA_SOURCE_2);
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
BigInteger count = (BigInteger) session.createSQLQuery("select count(*) from videoinfo").uniqueResult();
System.out.println(count);
session.getTransaction().commit();
return "result";
}
spring具有事务管理功能,不应该由我来进行事务的开启和关闭,那肯定是某个配置文件未配置好
解决:
在中添加以下属性
<property name="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</property>
(以上是针对Hibernate4,对于Hibernate3.x,可以直接把上述设置删除,就不会报错了)
配置session运行的上下文环境,绑定session。
在 SessionFactory 启动的时候, Hibernate 会根据配置创建相应的 CurrentSessionContext ,在 getCurrentSession() 被调用的时候,如果当前 Session 为空, currentSession 会调用 SessionFactory 的 openSession ,若不为空,则范文当前Session。
(一)getCurrentSession() 和 openSession()
1、getCurrentSession() 创建的session会和绑定到当前session上下文中,而openSession() 不会。
2、getCurrentSession() 创建的线程会在事务回滚或事物提交后自动关闭,而openSession() 必须手动关闭
(二)transaction和session
(三)OpenSessionInViewFilter
OpenSessionInViewFilter是一个Servlet2.3过滤器,用来把一个Hibernate Session和一次完整的请求过程对应的线程相绑定。目的是为了实现"Open Session in View"的模式。例如: 它允许在事务提交之后延迟加载显示所需要的对象。
(四)one session per request
session并不是线程安全的,不能被多线程共享
参考:
http://stackoverflow.com/questions/8046662/hibernate-opensession-vs-getcurrentsession
http://stackoverflow.com/questions/24468602/org-hibernate-hibernateexception-createsqlquery-is-not-valid-without-active-tra/24469155#24469155
http://blog.csdn.net/wzk527/article/details/8543480
blog.csdn.net/yinjian520/article/details/8666695