hibernate4与spring3整合时遇到no session found for current thread错误
在网上找了好多都说加上<prop key="current_session_context_class">thread</prop>这句就可以了,结果试了半天没试出来,后来无意中看到有人的配置是这样的
<prop key="hibernate.current_session_context_class">thread</prop>于是忽然想到是不是因为与spring整合,此配置写在了spring配置文件里不加hibernate不行,结果试了下果然成功了!汗!!!
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"><property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/news"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
</props>
</property>
</bean>
下面再记录两点关于getCurrentSession和openSession的区别:
1 getCurrentSession创建的session会和绑定到当前线程,而openSession不会。
2 getCurrentSession创建的线程会在事务回滚或事物提交后自动关闭,而openSession必须手动关闭
这里getCurrentSession本地事务(本地事务:jdbc)时 要在配置文件里进行如下设置
* 如果使用的是本地事务(jdbc事务)
<property name="hibernate.current_session_context_class">thread</property>
* 如果使用的是全局事务(jta事务)
<property name="hibernate.current_session_context_class">jta</property>
getCurrentSession () 使用当前的session
openSession() 重新建立一个新的session