spring控制事务的三种方式小结

网友投稿 267 2022-09-23


spring控制事务的三种方式小结

目录方式一:编码方式(需要修改源代码,基本不会用)方式二:xml配置(不需要改动代码,直接配置xml)方式三:注解spring是如何控制事务的?

首先准备环境,目录结构如下

数据库准备

业务层代码

@Service("accountService")

public class AccountServiceImpl implements AccountService {

@Resource(name = "accountDao")

AccountDao accountDao;

public void transfer(Integer from, Integer to, Float money) {

accountDao.subMoney(from,money);

int i = 1/0; //此处引发异常

accountDao.addMoney(to,money);

}

}

持久层代码

public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {

public void addMoney(Integer id, Float money) {

getJdbcTemplate().update("update account set money=money+? where id=?", money , id);

}

public void subMoney(Integer id, Float money) {

getJdbcTemplate().update("update account set money=money-? where id=?", money , id);

}

}

测试代码

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration("classpath:applicationContext.xml")

public class Test {

@Resource(name="accountService")

private AccountService accountService;

@org.junit.Test

public void test(){

accountService.transfer(1,2,100f);

}

}

运行结果

现在来用三种方式进行事务控制

方式一:编码方式(需要修改源代码,基本不会用)

添加事务管理类和事务模板类

修改业务层代码

@Service("accountService")

public class AccountServiceImpl implements AccountService {

@Resource(name = "accountDao")

AccountDao accountDao;

@Resource(name="transactionTemplate")

private TransactionTemplate transactionTemplate;

public void transfer(final Integer from, final Integer to, final Float money) {

transactionTemplate.execute(new TransactionCallbackWithoutResult() {

@Override

protected void doInTransactionWithoutResult(TransactionStatus status) {

accountDao.subMoney(from,money);

int i = 1/0;

accountDao.addMoney(to,moneydHNrhONpM);

}

});

}

}

方式二:xml配置(不需要改动代码,直接配置xml)

方式三:注解

首先开启注解管理aop事务,然后打注解

/*

* 该注解可以打在方法上,也可以打在类上

*/

@Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=false)

public void transfer(final Integer from, final Integer to, final Float money) {

accountDao.subMoney(from,money);

int i = 1/0;

accountDao.addMoney(to,money);

}

spring是如何控制事务的?

Spring 的事务,可以说是 Spring AOP 的一种实现。

AOPhttp://面向切面编程,即在不修改源代码的情况下,对原有功能进行扩展,通过代理类来对具体类进行操作。

spring是一个容器,通过spring这个容器来对对象进行管理,根据配置文件来实现spring对对象的管理。

spring的事务声明有两种方式,编程式和声明式。spring主要是通过“声明式事务”的方式对事务进行管理,即在配置文件中进行声明,通过AOP将事务切面切入程序,最大的好处是大大减少了代码量。


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:第一章 路由器是啥玩意?(第一章妲己的小说)
下一篇:数通十二年
相关文章

 发表评论

暂时没有评论,来抢沙发吧~