Transactions are discarded after an exception

When I throw an exception in a service method, I expected the transactional annotation for the service to perform a rollback operation, but it doesn't work.

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 the following 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 have declared the scan:

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

      

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

+3


source to share


4 answers


The problem was in the configuration, as I was declaring services and the transaction manager in different spring contexts: the transaction manager was in the root context, and the services were in the child dispatcher-servlet.xml context.



0


source


@Transactional(value = "transactionManagerForServiceLayer", rollbackFor = Exception.class)

      



This is a criminal. You shouldn't have another transaction manager for the service and repository. To fix this you need to replace transactionManagerForServiceLayer here with transactionManager and then the rollback will work.

+1


source


Try throwing an exception in OrderRepositoryImpl to see if it works

public class OrderRepositoryImpl implements OrderRepository {
    @Override
    public void save() {
        throw new SomeRunTimeException();
    }
}

public class OrderServiceImp implements OrderService {
    @Override
    public void doSomeStaff(Long orderId) {
        Order order = orderRepository.findOne(orderId);
        orderRepository.save(order);
    }
}

      

0


source


Autopost DataSource Enabled (or True). Disable it (or false).

0


source







All Articles