1 package com.atsyc.api.transaction; 2 3 //银行卡业务方法,调用dao方法 4 5 import org.junit.Test; 6 7 import java.sql.Connection; 8 import java.sql.DriverManager; 9 10 /* 11 * TODO: 12 * 事物添加是在业务方法中 13 * 利用try catch代码块,开启事务和提交事务,还有事务回滚 14 * 将connection传入dao层即可,dao只负责使用,不要close(); 15 */ 16 17 public class BankService { 18 19 @Test 20 public void start() throws Exception { 21 transfer("user1","user2",500); 22 } 23 24 public void transfer(String addAccount,String subAccount,int money) throws Exception { 25 BankDao bankDao = new BankDao(); 26 27 //一个事务的最基本要求,必须是同一个连接对象connection 28 29 //一个转账方法属于一个事务(加钱,减钱) 30 31 Class.forName("com.mysql.cj.jdbc.Driver"); 32 Connection connection = DriverManager.getConnection("jdbc:mysql:///atsyc","root","Yican030615"); 33 34 try{ 35 //开启事务(从业务层开启) 36 37 //关闭事务提交 38 connection.setAutoCommit(false); 39 40 //执行数据库动作 41 bankDao.add(addAccount,money,connection); 42 System.out.println("----------"); 43 bankDao.sub(subAccount,money,connection); 44 45 //事务提交 46 connection.commit(); 47 }catch (Exception e) { 48 //事务回滚 49 connection.rollback(); 50 //抛出异常信息 51 throw e; 52 }finally { 53 { 54 connection.close(); 55 } 56 } 57 } 58 }
标签:事务,JDBC,money,数据库,dao,connection,bankDao,import From: https://www.cnblogs.com/IrVolcano/p/18056476