spring启用注解事务@Transactional操作

这篇文章记录启用注解事务@Transactional配置

一、准备工作

1)引入相关jar包


	mysql
	mysql-connector-java
	5.1.34



	org.springframework
	spring-jdbc
	${spring.version}



	org.springframework
	spring-tx
	${spring.version}

2)引入相关约束



二、XML配置事务





	
	

	
	
		
		
		
		
	
	
	
	
		
	

	
	
		
	

	
	
	

三、转账案例测事务

1)创建账户表

CREATE TABLE `tb_account` (
  `id` int(11) NOT NULL COMMENT '账号id',
  `name` varchar(10) NOT NULL COMMENT '姓名',
  `money` double NOT NULL DEFAULT '0' COMMENT '金额',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

INSERT INTO `tb_account` VALUES (1, '张三', 10000);
INSERT INTO `tb_account` VALUES (2, '李四', 10000);

2)编写AccountService模拟转账

package lzgsea.jdbc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("accountService")
public class AccountService {
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@Transactional
	public void transfer() {
		System.out.println("开始转账");
		String sql = "update tb_account set money = money + ? where id = ?";
		jdbcTemplate.update(sql, -1000,1);
		//异常 测试是否回滚
		int i = 1/0;
		jdbcTemplate.update(sql, 1000,2);
		System.out.println("操作完成");
	}
}

3)测试

ApplicationContext act = new ClassPathXmlApplicationContext("transactional.xml");
AccountService accountService = (AccountService) act.getBean("accountService");
accountService.transfer();


你可能感兴趣的:(spring)