天天看點

事務控制

示範代碼:

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
@Service
@Transactional(value = "transactionManager")
//@Transactional(value = "transactionManager",rollbackFor=Exception.class)
public class WooTestServiceImpl implements WooTestService {

    public String testTrans(){
        try{

        }catch (Exception e ){               
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            throw new RuntimeException();
        }
    }
}
           

1、僅有 @Transactional(value = "transactionManager") 或 僅有 @Transactional(value = "transactionManager",rollbackFor=Exception.class),

更新多條資料,若中間某條資料某個字段更新失敗-出現Exception,該條資料的其他字段也會被更新,且後續資料也更新,資料不會復原

2、僅有 throw new RuntimeException(); 或 僅有 TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();時:

更新多條資料,若中間某條資料某個字段更新失敗-出現Exception,該條資料的其他字段也會被更新,但後續資料不會更新,資料不會復原

3、@Transactional(value = "transactionManager") + TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

若有資料更新失敗,資料會全部復原

4、@Transactional(value = "transactionManager") + throw new RuntimeException();

若有資料更新失敗,資料會全部復原

5、

@Autowired
private PlatformTransactionManager transactionManager;

DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setPropagationBehavior( TransactionDefinition.PROPAGATION_REQUIRES_NEW );// 事務隔離級别,開啟新事務
TransactionStatus statusTran = transactionManager.getTransaction( def );//擷取事務狀态,并開啟事務,相當于transation.begin();
transactionManager.commit( statusTran ); //送出事務