java mysql多次事务 模拟依据汇率转账,并存储转账信息 分层完成 dao层 service 层 client层 连接池使

Jar包使用,及层的划分

c3p0-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
    <!-- 默认配置,如果没有指定则使用这个配置
        默认配置最常用
        
        建议放在最开头。
        放其他地方也没问题
     -->
    <default-config>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/test2</property>
        <property name="user">root</property>
        <property name="password">root</property>
        <property name="checkoutTimeout">30000</property>
        <property name="idleConnectionTestPeriod">30</property>
        <property name="initialPoolSize">10</property>
        <property name="maxIdleTime">30</property>
        <property name="maxPoolSize">100</property>
        <property name="minPoolSize">10</property>
        <property name="maxStatements">200</property>
        <user-overrides user="test-user">
            <property name="maxPoolSize">10</property>
            <property name="minPoolSize">1</property>
            <property name="maxStatements">0</property>
        </user-overrides>
    </default-config>
    
    
</c3p0-config>

JDBCUtils

package cn.itcast.tools;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/*a). 私有,静态成员变量:ComboPooledDataSource 并创建对象;加载配置文

件的默认配置。

b). 公有,静态成员方法:public static DataSource getDataSource(),此方法返

回C3P0连接池对象;

c). 公有,静态成员方法:public static Connection getConnection(),此方法返回

通过C3P0连接池获取的Connection对象;使用本地线程 ThreadLocal*/

public class JDBCUtils {

    private static ComboPooledDataSource dataSource =new ComboPooledDataSource();
    
    private static ThreadLocal<Connection> local=new ThreadLocal<Connection>();
    
    
    public static DataSource getDataSource() {
        
        return dataSource;
        
    }
    
    public static Connection getConnection(){
        
        Connection con=local.get();
        if(con==null) {
            try {
                con=dataSource.getConnection();
                local.set(con);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            con=local.get();
        }
        return con;
        
    }
    
    public static void close(Connection con,Statement st,ResultSet rs) {
        
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (st != null) {
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

dao

package com.swift.dao;

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import cn.itcast.domain.Account;
import cn.itcast.tools.JDBCUtils;

public class Dao {

    private QueryRunner qr = new QueryRunner();
    private Connection con=JDBCUtils.getConnection();
    
    public void querySenderBalance(String cardid1, double money) throws SQLException {

        
        String sql = "SELECT * FROM account WHERE cardid=?;";
        BeanHandler<Account> rsh = new BeanHandler<Account>(Account.class);
        Account bean = qr.query(con, sql, rsh, cardid1);
        System.out.println(bean);
        double balance = bean.getBalance();
        System.out.println(balance);
        if (balance < money) {
            System.out.println("余额不足!");
            System.exit(0);
        } else {
            System.out.println("余额足够了!");
        }
    }
    
    public int zhuanchu(String cardid, double money) throws SQLException {
        
        String chaxun = "select moneyRate from account where cardid=?";
        double rate=(double) qr.query(con,chaxun, new ScalarHandler(),cardid);
        double moneyRate=money*rate/100;
        System.out.println(moneyRate);
        String shengyu = "UPDATE account SET balance =balance-?-? WHERE cardid=?;";
        return qr.update(con, shengyu, money,moneyRate,cardid);
        
    }
    public int zhuanru(String cardid, double money) throws SQLException {
        
        String zengjia = "UPDATE account SET balance =balance+? WHERE cardid=?;";
        return qr.update(con, zengjia, money,cardid);
        
    }
    public int writeInfo(String cardid, String tratype,double money,String tradate) throws SQLException {
        
        String info = "insert into transaction(cardid,tratype,tramoney,tradate) values(?,?,?,?);";
        return qr.update(con, info, cardid,tratype,money,tradate);
        
    }
    
    
    
    
}

Service

package com.swift.service;

import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.swift.dao.Dao;

import cn.itcast.tools.JDBCUtils;

public class Service {

    private Connection con=JDBCUtils.getConnection();
    
    public void transfer(String cardid1, String cardid2, double money) {

        try {
            
            con.setAutoCommit(false);
            Dao dao=new Dao();
            dao.querySenderBalance(cardid1, money);
            int chu=dao.zhuanchu(cardid1, money);
            int ru=dao.zhuanru(cardid2, money);
            con.commit();
            if(chu>0&&ru>0) {
                System.out.println("转账成功.");
            }
            Date date=new Date();
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String tradate=sdf.format(date);
            dao.writeInfo(cardid1, "转出", money, tradate);
            dao.writeInfo(cardid2, "转入", money, tradate);
            con.commit();
        } catch (Exception e) {
            System.out.println("出现异常准备回滚.");
            e.printStackTrace();
            try {
                con.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        } finally {
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

client

package com.swift.client;

import com.swift.service.Service;

public class Client {

    public static void main(String[] args) {

        String cardid1 = "6212999999999";
        String cardid2 = "6212888888888";
        double money = 600;
        
        Service s=new Service();
        s.transfer(cardid1, cardid2, money);
        
    }

}