Search code examples
javaspringspring-data-jpaspring-transactions

Rolling back transactions after exception is thrown


When I throw exception in service method I expected that transactional annotation on service will rollback save operation, but it is not working.

This is my service:

  @Service
  @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public class OrderServiceImp implements OrderService {
        @Autowired
        private OrderRepository orderRepository;

        @Override
        public void doSomeStaff(Long orderId) {
             Order order = orderRepository.findOne(orderId);
             orderRepository.save(order);
             throw new NullPointerException("Test transaction exeption");
        }
    }

In data.xml I have next configs:

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

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>


<jpa:repositories base-package="com.dmitro.repositories" entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="transactionManager"/>

In dispatcher-servlet.xml I declared scan:

<context:component-scan base-package="com.dmitro.service" />

I am using spring-data-jpa 1.8.0.RELEASE. Please help!


Solution

  • Problem was in configuration, because I declared services and transaction manager in different spring contexts: transaction manager was in root context and services was in child dispatcher-servlet.xml context.