Spring事务

Spring 支持两种事务方式,分别是编程式事务和声明式事务,后者最常见

声明式

@Transactional
public void handle() {
 // 转账
 transfer(double money);
 // 减自己的钱
  Reduce(double money);
}

编程式

使用 TransactionTemplate 来管理事务

@Autowired
private TransactionTemplate transactionTemplate;
public void testTransaction() {

        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {

                try {

                    // ....  业务代码
                } catch (Exception e){
                    //回滚
                    transactionStatus.setRollbackOnly();
                }

            }
        });
}

使用 TransactionManager 来管理事务

就编程式事务管理而言,Spring 更推荐使用 TransactionTemplate。

MongoDB

mongoDB整合spring使用注解

Last updated