Spring @Transactional rollbackFor not working

爷,独闯天下 提交于 2019-12-20 02:52:37

问题


I have a code like below

   public abstract class AffltTransactionService implements IAffltTransactionService {
    ....

        @Override
        @Transactional
        public void processTransactions(List<? extends AffltTransaction> transactions) {
            for (AffltTransaction transaction : transactions) {
                if (transaction != null) {
                    processTransaction(transaction);
                }
            }
        }

        private void processTransaction(AffltTransaction transaction) {
            try {
                processTransactionInternal(transaction);

            } catch (Exception exception) {
                affltTransactionError = new AffltTransactionError(null, null, "error", new Date());
                saveAffltTransactionError(affltTransactionError);
                log.error(exception.getLocalizedMessage());
            }
        }

        @Transactional(readOnly=false, rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
        public void processTransactionInternal(AffltTransaction transaction) {

processTransactionInternal throws ServiceUnAvailableException which extends RuntimeException

But the transaction is not getting rolled back despite having rollbackFor = Exception.class . Can you please help.


回答1:


@Transactional annotation won't have any effect if you are calling the method directly, since Spring creates proxies above annotated classes and the aspect-defined functionality is implemented by proxy. So, when you call the method from within your class it doesn't get through proxy, and hence no transcation is created and/or rolled back.

Take a look at the Spring reference for detailed explanation.




回答2:


Since you invoke one method from another within the same bean, the Spring AOP doesn't use any advices in this case.

Only processTransactions is wrapped with TransactionInteceptor.

To make it worked you should configure:

<aop:aspectj-autoproxy expose-proxy="true"/>

But it isn't recommened, though.

More info here: http://www.intertech.com/Blog/secrets-of-the-spring-aop-proxy




回答3:


Use getCurrentSession instead of opensession




回答4:


The method you use apply @Transactional should throws exception. Don't use try-catch instead.(I guess you use try-catch in somewhere in your processTransaction function). Code should be like this:

@Transactional
    public void processTransactions(List<? extends AffltTransaction> transactions) threws Exception{
        for (AffltTransaction transaction : transactions) {
            if (transaction != null) {
                processTransaction(transaction);
            }
        }
    }


来源:https://stackoverflow.com/questions/22957569/spring-transactional-rollbackfor-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!