以经典的转账业务举例
创建数据库
Create Table
CREATE TABLE `t_bank` (
`id` int NOT NULL AUTO_INCREMENT,
`account` varchar(20) DEFAULT NULL,
`money` int unsigned DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
插入两条数据
新建一个transaction包
BankDao
package com.transaction;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
/**
* bank表的数据库操作方法存储类
*/
public class BankDao {
/**
* 加钱的方法
* @param account
* @param money
* @param connection
*/
public void add(String account, int money, Connection connection) throws Exception {
Class.forName("com.mysql.cj.jdbc.Driver");
//Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "123456");
String sql = "update t_bank set money = money + ? where account = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setObject(1, money);
statement.setObject(2, account);
statement.executeUpdate();
statement.close();
System.out.println("加钱成功!");
}
/**
* 减钱的方法
* @param account
* @param money
* @param connection
*/
public void sub(String account, int money, Connection connection) throws Exception {
Class.forName("com.mysql.cj.jdbc.Driver");
//Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "123456");
String sql = "update t_bank set money = money - ? where account = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setObject(1, money);
statement.setObject(2, account);
statement.executeUpdate();
statement.close();
System.out.println("减钱成功!");
}
}
BankService
package com.transaction;
import org.junit.jupiter.api.Test;
import java.sql.Connection;
import java.sql.DriverManager;
public class BankService {
/**
* 转账的方法
* @param addAccount
* @param subAccount
* @param money
*/
public void transfer(String addAccount, String subAccount, int money) throws Exception {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "123456");
BankDao bankDao = new BankDao();
try {
// 关闭自动提交
connection.setAutoCommit(false);
bankDao.add(addAccount, money, connection);
bankDao.sub(subAccount, money, connection);
System.out.println("转账完成!");
connection.commit();
} catch (Exception e){
connection.rollback();
throw e;
} finally {
connection.close();
}
}
@Test
public void start() throws Exception {
transfer( "lvdd", "ergouzi",500);
}
}
运行结果
加钱成功!
减钱成功!
转账完成!
Process finished with exit code 0