Spring - @Transactional не запускает транзакцию

1

Раньше у меня был BaseDAO с методом getTransaction() и commitTransaction(), который служил транзакции. Но когда я добавляю отношения @OneToMany с ленивой загрузкой, у меня были ошибки, связанные с отсутствием сеанса и т.д. Поэтому я решил использовать аннотацию @Transactional для моих методов EmployerService:

package services;

import daos.interfaces.InterfaceEmployerDAO;
import dtos.EmployerDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import services.interfaces.InterfaceEmployerService;
import transformers.interfaces.InterfaceEmployerTransformer;

import java.util.List;

public class EmployerService implements InterfaceEmployerService {
    @Autowired
    private InterfaceEmployerDAO employerDAO;
    @Autowired
    private InterfaceEmployerTransformer employerTransformer;

    @Override
    @Transactional
    public List<EmployerDTO> getAllEmployers() {
        return employerTransformer.listToDTO(employerDAO.getAllEmployers());
    }

    (methods irrevelant at this moment)
}

И <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/> был добавлен в файл applicationContext.xml (я вставляю все, потому что я новичок в Spring Annotations, и я не знать, что может быть важно для решения проблемы, я приношу свои извинения за беспорядок):

    <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                http://www.springframework.org/schema/context
                http://www.springframework.org/schema/context/spring-context.xsd
                http://www.springframework.org/schema/tx
                http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
                http://www.springframework.org/schema/mvc
                http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

       <!-- Data Source Declaration -->
       <bean id="DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
              <property name="driverClass" value="org.postgresql.Driver" />
              <property name="jdbcUrl" value="jdbc:postgresql://localhost:5432/postgres" />
              <property name="user" value="postgres" />
              <property name="password" value="postgres" />
              <property name="maxPoolSize" value="10" />
              <property name="maxStatements" value="0" />
              <property name="minPoolSize" value="5" />
       </bean>

       <!-- Session Factory Declaration -->
       <bean id="SessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
              <property name="dataSource" ref="DataSource" />
              <property name="annotatedClasses">
                     <list>
                            <value>models.Employee</value>
                            <value>models.Employer</value>
                     </list>
              </property>
              <property name="hibernateProperties">
                     <props>
                            <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
                            <prop key="hibernate.connection.driver_class">org.postgresql.Driver</prop>
                            <prop key="hibernate.connection.url">jdbc:postgresql://localhost:5432/postgres</prop>
                            <prop key="hibernate.connection.username">postgres</prop>
                            <prop key="hibernate.connection.password">postgres</prop>
                            <prop key="hibernate.show_sql">true</prop>
                            <prop key="hibernate.current_session_context_class">thread</prop>
                            <prop key="hibernate.query.factory_class">org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory</prop>
                            <prop key="hibernate.hbm2ddl.auto">update</prop>
                            <prop key="hibernate.search.default.directory_provider">filesystem</prop>
                            <prop key="hibernate.search.default.indexBase">target/luceneIndex</prop>
                     </props>
              </property>
       </bean>

       <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
              <property name="sessionFactory" ref="SessionFactory"></property>
       </bean>
       <bean class="services.EmployeeService"></bean>
       <bean class="services.EmployerService"></bean>
       <bean class="daos.EmployeeDAO"></bean>
       <bean class="daos.EmployerDAO"></bean>
       <bean class="transformers.EmployeeTransformer"></bean>
       <bean class="transformers.EmployerTransformer"></bean>

       <context:annotation-config/>
       <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
       <context:component-scan base-package="controllers" />

       <mvc:annotation-driven/>

</beans>

Я думал, что HibernateTransactionManager и tx:annotation-driven заставили его работать, но я ошибся - я получил: **createCriteria is not valid without active transaction** в методе daos.EmployerDAO.getAllEmployers. Я уверен, что я не могу правильно настроить transactionManager. Я был бы очень рад, если кто-нибудь решит помочь мне - спасибо заранее. Я также представляю mvc-dispatcher-servlet.xml, возможно, что-то не так:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                http://www.springframework.org/schema/context
                http://www.springframework.org/schema/context/spring-context.xsd
                http://www.springframework.org/schema/mvc
                http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">


       <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
              <property name="prefix">
                     <value>/</value>
              </property>
              <property name="suffix">
                     <value>.jsp</value>
              </property>
       </bean>

</beans>

Еще раз спасибо за любую помощь.

Решение найдено, см. Мой ответ ниже.

Теги:
spring
spring-mvc
hibernate
transactions

1 ответ

0
Лучший ответ

Я думаю, что нашел решение здесь: "весна, спящий режим и декларативная транзакция: нет активной транзакции". Мне нужно удалить эту строку:

<prop key="hibernate.current_session_context_class">thread</prop>

Потому что он отключает управление транзакциями Spring.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню