HTTP状态500 - 请求处理失败;嵌套异常是org.hibernate.HibernateException:没有Hibernate Session绑定到线程

时间:2013-11-30 10:21:24

标签: java spring hibernate session transactions

我写测试弹簧应用程序。我有问题。

我的java代码:

控制器方法

    @RequestMapping(value = "/index")
    public String setupForm()
    {    
        mainService.getAllRecords());
    }

服务接口

@Transactional
public interface MainService
{

    public List<Record> getAllRecords();
}

服务impl

@Service("mainService")
@Transactional
public class MainServiceImpl implements MainService
{
    @Autowired
    private MainDao mainDao;


    @Transactional
    public List<Record> getAllRecords()
    {

        return mainDao.getAllRecords();
    }

}

dao没有标记为@Transactional。

我看到下一个错误:

HTTP Status 500 - Request processing failed; nested exception is org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

如果我将dao界面标记为@Transactional - 它运作良好。

配置:

的web.xml

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/root-context.xml</param-value>
    </context-param> 

    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- Processes application requests -->
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

data.xml中

<!-- Настраивает управление транзакциями с помощью аннотации @Transactional -->
    <tx:annotation-driven transaction-manager="transactionManager" />
    <!-- Менеджер транзакций -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>
    <!-- Настройки бина dataSource будем хранить в отдельном файле -->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" p:location="/WEB-INF/jdbc.properties" />
    <!-- Непосредственно бин dataSource -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" p:driverClassName="${jdbc.driverClassName}"
        p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}" />
    <!-- Настройки фабрики сессий Хибернейта -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.dialect">${jdbc.dialect}</prop>
                <prop key="hibernate.connection.charSet">UTF-8</prop>
                <prop key="hibernate.hbm2ddl.auto">create</prop>
            </props>
        </property>
    </bean>

根context.xml中

<context:component-scan base-package="com.wp.crud.dao"/>
<context:component-scan base-package="com.wp.crud.controller"/>

<!--
 Файл с настройками ресурсов для работы с данными (Data Access Resources) 
-->
 <import resource="data.xml"/>   

servlet的context.xml中

<annotation-driven />

    <!-- Всю статику (изображения, css-файлы, javascript) положим в папку webapp/resources и замаппим их на урл вида /resources/** -->

    <resources mapping="/resources/**" location="/resources/" />
    <!-- Отображение видов на jsp-файлы, лежащие в папке /WEB-INF/views -->

    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>
    <!-- Файл с настройками контроллеров -->

    <beans:import resource="controllers.xml" />

controllers.xml

<context:component-scan base-package="com.wp.crud.controller"/>

我不明白这个问题的原因。

你可以帮帮我吗?

3 个答案:

答案 0 :(得分:1)

在你的web.xml中,你缺少声明Hibernate OpenSessionInViewFilter,它使你的hibernate会话在你的请求过程中打开:

<filter>
        <filter-name>hibernateFilter</filter-name>
        <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
        <init-param>
            <param-name>singleSession</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>hibernateFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

这应该可以解决您的错误。 请注意,过滤器类适用于Hibernate4,需要在Hibernate3

的情况下进行修复

答案 1 :(得分:0)

<context:component-scan base-package="com.wp.crud.controller"/>

您是否真的需要root-context.xmlcontrollers.xml中的这一行?

我认为您首先应该通过服务包替换com.wp.crud.controller中的root-context.xml(如果尚未更换)。

此外,您应该将这些组件扫描放在data.xml的这一行之后的某个位置:

<tx:annotation-driven transaction-manager="transactionManager" />

因此@Transactional注释可能会对扫描的类产生影响。

顺便说一句,您在服务界面上不需要@Transactional

答案 2 :(得分:0)

<tx:annotation-driven transaction-manager="txManager"/>
    <!-- Transaction Manager is defined -->
    <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
</bean>

在库中添加此jar文件 aopalliance-1.0.jar