以下是一个基于Java和MySQL的简易银行交易系统实现方案,包含存款、取款、转账的核心开发流程:

数据库设计

创建MySQL数据库表结构,主要包含账户表和交易记录表:

CREATE TABLE accounts (
    account_id VARCHAR(20) PRIMARY KEY,
    account_name VARCHAR(50) NOT NULL,
    balance DECIMAL(15,2) DEFAULT 0.00,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE transactions (
    transaction_id INT AUTO_INCREMENT PRIMARY KEY,
    account_id VARCHAR(20),
    transaction_type ENUM('DEPOSIT', 'WITHDRAW', 'TRANSFER'),
    amount DECIMAL(15,2),
    target_account VARCHAR(20),
    transaction_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (account_id) REFERENCES accounts(account_id)
);

Java核心类实现

数据库连接管理
public class DBConnection {
    private static final String URL = "jdbc:mysql://localhost:3306/bank_system";
    private static final String USER = "root";
    private static final String PASSWORD = "password";

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL, USER, PASSWORD);
    }
}

账户操作类
public class AccountDAO {
    public boolean deposit(String accountId, double amount) {
        String sql = "UPDATE accounts SET balance = balance + ? WHERE account_id = ?";
        
        try (Connection conn = DBConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            pstmt.setDouble(1, amount);
            pstmt.setString(2, accountId);
            int affectedRows = pstmt.executeUpdate();
            
            if (affectedRows > 0) {
                recordTransaction(accountId, "DEPOSIT", amount, null);
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    private void recordTransaction(String accountId, String type, double amount, String targetAccount) {
        String sql = "INSERT INTO transactions (account_id, transaction_type, amount, target_account) VALUES (?, ?, ?, ?)";
        
        try (Connection conn = DBConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            pstmt.setString(1, accountId);
            pstmt.setString(2, type);
            pstmt.setDouble(3, amount);
            pstmt.setString(4, targetAccount);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

交易服务类
public class TransactionService {
    private AccountDAO accountDAO = new AccountDAO();

    public boolean transfer(String fromAccount, String toAccount, double amount) {
        if (amount <= 0) return false;
        
        try (Connection conn = DBConnection.getConnection()) {
            conn.setAutoCommit(false);
            
            // 检查余额是否充足
            if (!checkBalance(fromAccount, amount)) {
                return false;
            }
            
            // 执行转账
            if (accountDAO.withdraw(fromAccount, amount) && 
                accountDAO.deposit(toAccount, amount)) {
                
                // 记录交易
                accountDAO.recordTransaction(fromAccount, "TRANSFER", amount, toAccount);
                conn.commit();
                return true;
            }
            conn.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    private boolean checkBalance(String accountId, double amount) {
        String sql = "SELECT balance FROM accounts WHERE account_id = ?";
        
        try (Connection conn = DBConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            pstmt.setString(1, accountId);
            ResultSet rs = pstmt.executeQuery();
            
            if (rs.next()) {
                return rs.getDouble("balance") >= amount;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }
}

业务逻辑实现

存款操作
public boolean withdraw(String accountId, double amount) {
    if (amount <= 0) return false;
    
    String sql = "UPDATE accounts SET balance = balance - ? WHERE account_id = ? AND balance >= ?";
    
    try (Connection conn = DBConnection.getConnection();
         PreparedStatement pstmt = conn.prepareStatement(sql)) {
        
        pstmt.setDouble(1, amount);
        pstmt.setString(2, accountId);
        pstmt.setDouble(3, amount);
        int affectedRows = pstmt.executeUpdate();
        
        if (affectedRows > 0) {
            recordTransaction(accountId, "WITHDRAW", amount, null);
            return true;
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return false;
}

异常处理

添加自定义异常类处理业务异常:

public class InsufficientBalanceException extends Exception {
    public InsufficientBalanceException(String message) {
        super(message);
    }
}

public class InvalidAmountException extends Exception {
    public InvalidAmountException(String message) {
        super(message);
    }
}

事务管理

确保操作的原子性,使用JDBC事务:

public boolean performTransaction(String fromAccount, String toAccount, double amount) 
    throws InsufficientBalanceException, InvalidAmountException {
    
    if (amount <= 0) {
        throw new InvalidAmountException("Amount must be positive");
    }
    
    try (Connection conn = DBConnection.getConnection()) {
        conn.setAutoCommit(false);
        
        if (!checkBalance(fromAccount, amount)) {
            throw new InsufficientBalanceException("Insufficient balance");
        }
        
        if (withdraw(fromAccount, amount) && deposit(toAccount, amount)) {
            recordTransaction(fromAccount, "TRANSFER", amount, toAccount);
            conn.commit();
            return true;
        }
        conn.rollback();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return false;
}

安全注意事项

  1. 使用PreparedStatement防止SQL注入
  2. 敏感操作需要身份验证
  3. 重要操作记录详细日志
  4. 数据库连接使用连接池管理
  5. 金额使用BigDecimal避免精度问题

这个实现包含了银行系统核心功能,可根据实际需求扩展账户管理、利息计算、交易查询等功能。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐