查找资料:问题分析
Hibernate4 No Session found for current thread原因
解决办法:
1. 在spring 配置文件中加入
<tx:annotation-driven transaction-manager="transactionManager"/>
并且在处理业务逻辑的类上采用注解
<pre name="code" class="html">@Service
public class CustomerServiceImpl implements CustomerService {
@Transactional
public void saveCustomer(Customer customer) {
customerDaoImpl.saveCustomer(customer);
}
...
}
2另外在 hibernate 的配置文件中,也可以增加这样的配置来避免这个错误
<property name="current_session_context_class">thread</property>
3在spring配置文件中配置SessionFactory
<!-- 配置SessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<!-- 直接使用hibernate的核心配置文件 -->
<!--<property name="configLocation"></property>-->
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<span style="color:#009900;"><span style="background-color: rgb(51, 51, 153);"><prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext
</prop></span></span>
</props>
</property>
<!--
<property name="mappingLocations" value="classpath:com/itany/entity/*.hbm.xml"> </property>
-->
<!--扫包-->
<property name="packagesToScan">
<list>
<value>com.itany.entity</value>
</list>
</property>
</bean>
解决方法二: SpringMVC4+Hibernate4运行报错Could not obtain transaction-synchronized Session for current thread来自百度
在web.xml中加一个过滤器
<filter>
<filter-name>SpringOpenSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SpringOpenSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
我是用方法二解决的