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
@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 to share
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 to share