1

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?

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

5 Comments

it is working advice. But I cannot understand what the problem was solved after addin this snippet to web.xml
OpenSessionInViewFilter is a web filter that opens an hibernate session anytime you make a request and bound it to your threadlocal. So in your dao you can always call sessionFactory.getCurrentSession()
seems, I saw examples with @Transactional and without this filter. Can it be true?
I have found my old project and there are I use hibernate+spring+transactional
i've always used this filter with hibernate.. so i don't know exactly how it works without it.. sorry..
0
<context:component-scan base-package="com.wp.crud.controller"/>

Do you really need this line in both root-context.xml and controllers.xml?

I think first you should replace (if not already replaced) com.wp.crud.controller in root-context.xml by your service package.

And also you should place these component scans somewhere after this line from data.xml:

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

so @Transactional annotation could have effect on scanned classes.

By the way, you don't need @Transactional on service interface.

6 Comments

usually i exclude controllers from root context, placing them into servlet context.
@EmanueleRighetto it's ok, but there are now two component-scans for controllers package and I can't see any for services
yep, u're right, i didn't noticed that one component scan is only picking up dao
Sorry, max. I know that it is bad But my controllers and services are located in same package.
@gstackoverflow so you made changes only in web.xml, an now it works?
|
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>

Add this jar file in library
aopalliance-1.0.jar

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.