gstackoverflow gstackoverflow - 3 months ago 28
Java Question

HTTP Status 500 - Request processing failed; nested exception is org.hibernate.HibernateException: No Hibernate Session bound to thread

I write test spring application. I have problem.

my java code:

controller method

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


service interface

@Transactional
public interface MainService
{

public List<Record> getAllRecords();
}


service impl

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


@Transactional
public List<Record> getAllRecords()
{

return mainDao.getAllRecords();
}

}


dao doesn't mark as @Transactional.

I see next error:

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


If I mark dao interface as @Transactional - it works good.

Configuration:

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>


root-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"/>


I don't understand cause of this problem.

can you help me?

Answer

In your web.xml you are missing to declare Hibernate OpenSessionInViewFilter, that provides your hibernate session to be open within your request process:

<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>

This should fix your error. Please note that the filter class is for Hibernate4, you need to fix in case of Hibernate3