spring boot2 实现事务管理

基本配置见上一篇博客

spring boot实现数据库的事务功能很简单,只需要在需要事务方法或类上添加@Transactiona注解即可。

看下面的例子:

首先建立account数据库表,并确保类型为InnoDB(默认是MyISAM不支持事务):

                

 

创建AccountDao接口

public interface AccountDao {
 public void transfer(String accounta, String accountb, double m) ;
 public void transfer2(String accounta, String accountb, double m) ;
}

 编写AccountDao实现类AccountDaoImpl

@Repository
//@Transactional   //标注在此处表示类所有方法都有事务功能
public class AccountDaoImpl implements AccountDao {
    @Resource
    JdbcTemplate jdbct; 
	
	@Override
	@Transactional  //给该方法提供事务功能
	public void transfer(String accounta, String accountb, double m) {
                System.out.println("this is transfer method");
		String str1="update account set balance= balance+? where username=?";
		jdbct.update(str1,m,accountb);
		int testi=1/0;//有意设置除零错误,以测试事务要么该方法内的数据库操作全执行,要么一条也不执行
		str1="update account set balance= balance-? where username=?";
		jdbct.update(str1,m,accounta);		
	}
	
	//@Transactional  //给该方法提供事务功能
	public void transfer2(String accounta, String accountb, double m) {
                System.out.println("this is transfer2 method");
		String str1="update account set balance= balance+? where username=?";
		jdbct.update(str1,m,accountb);
		int testi=1/0; //有意设置除零错误,以测试事务要么该方法内的数据库操作全执行,要么一条也不执行
		str1="update account set balance= balance-? where username=?";
		jdbct.update(str1,m,accounta);		
	}

}

上面用了JdbcTemplate,使用@Resource和Autowired注入都可以,二者区别在于:

 

@Resource是Java自己的注解,@Resource有两个属性是比较重要的,分是name和type;Spring将@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。所以如果使用name属性,则使用name自动注入;使用type属性时则使用type自动注入策略。如果既不指定name也不指定type属性(即默认设置),这时使用name自动注入策略。
    @Autowired是spring的注解,Autowired只根据type进行注入,不会去匹配name。如果type无法辨别注入对象时,那需要依赖@Qualifier或@Primary注解一起来修饰。

在src/test/java下面的DemoApplicationTests中编写测试方法

@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
	@Autowired
	AccountDao accountDao;

	@Test
	public void contextLoads() {
		try { //try catch是为了能够继续运行transfer2方法
			System.out.println("begin transfer");
			accountDao.transfer("zhang", "li", 200);
			System.out.println("transfer end");
		} catch (Exception e) {
		}

		System.out.println("begin transfer2");
		accountDao.transfer2("zhang", "li", 100);
		System.out.println("transfer2 end");
	}
}

 

运行前后对比数据库记录

运行前                                                                                  运行后

控制台输出

可以看出,account表中username为li的记录增加了100,说明只有transfer 方法有事务功能,而transfer2 则没有。大家取消AccountDaoImpl 上面的@Transactional注解,并且注释掉transfer前面的@Transactional注解,看看数据库表的结果怎么样?

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值