使用DBUtil框架实现事务的处理

项目中各类的结构:
这里写图片描述
1.AccountDao接口:

package com.itheima.dao;

public interface AccountDao {
    /**
     * 转账
     * @param sourceAccountName 转出账户
     * @param targetAccontName 转入账户
     * @param money 交易金额
     */
    void transfer(String sourceAccountName,String targetAccontName,float money);
}

2。AccountDaoImpl类:

package com.itheima.dao.impl;

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

import org.apache.commons.dbutils.QueryRunner;

import com.itheima.dao.AccountDao;
import com.itheima.util.DBCPUtil;
/*
create table account(
    id int primary key auto_increment,
    name varchar(40),
    money float
)character set utf8 collate utf8_general_ci;

insert into account(name,money) values('aaa',1000);
insert into account(name,money) values('bbb',1000);
insert into account(name,money) values('ccc',1000);
 */
public class AccountDaoImpl implements AccountDao {
    private QueryRunner qr = new QueryRunner();
    public void transfer(String sourceAccountName, String targetAccontName,
            float money) {
        Connection conn = null;
        try {
            conn = DBCPUtil.getConnection();
            conn.setAutoCommit(false);//开启事务
            qr.update(conn,"update account set money=money-? where name=?", money,sourceAccountName);
            int i=1/0;
            qr.update(conn,"update account set money=money+? where name=?", money,targetAccontName);
        } catch (Exception e) {
            if(conn!=null){
                try {
                    conn.rollback();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
            }
            e.printStackTrace();
        }finally{
            if(conn!=null){
                try {
                    conn.commit();
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}

3.BusinessService接口:

package com.itheima.service;

public interface BusinessService {
    /**
     * 转账
     * @param sourceAccountName 转出账户
     * @param targetAccontName 转入账户
     * @param money 交易金额
     */
    void transfer(String sourceAccountName,String targetAccontName,float money);
}

4.BusinessServiceImpl类:

package com.itheima.service.impl;

import com.itheima.dao.AccountDao;
import com.itheima.dao.impl.AccountDaoImpl;
import com.itheima.service.BusinessService;

public class BusinessServiceImpl implements BusinessService {
    private AccountDao dao = new AccountDaoImpl();
    public void transfer(String sourceAccountName, String targetAccontName,
            float money) {
        dao.transfer(sourceAccountName, targetAccontName, money);
    }

}

5.DBCPUtil类:

package com.itheima.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;

public class DBCPUtil {

    private static DataSource dataSource;
    static{
        try {
            InputStream in = DBCPUtil.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
            Properties props = new Properties();
            props.load(in);
            dataSource = BasicDataSourceFactory.createDataSource(props);
        } catch (Exception e) {
            throw new ExceptionInInitializerError(e);
        }
    }
    public static DataSource getDataSource(){
        return dataSource;
    }

    public static Connection getConnection(){
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

6.Client类(模拟用户层):

package com.itheima.view;

import com.itheima.service.BusinessService;
import com.itheima.service.impl.BusinessServiceImpl;

public class Client {

    public static void main(String[] args) {
        BusinessService s = new BusinessServiceImpl();
        s.transfer("aaa", "bbb", 100);
    }

}
package com.parddu.dao; import java.io.IOException; import java.sql.*; import java.util.Properties; /** * 数据库功能类 * @author parddu * @version Sep 29, 2010 9:49:31 AM */ class DButil { private String driver=null; //驱动 private String dbName=null; //数据库名 private String host=null; //主机名 private String point=null; //端口 private String userName=null; //登录帐号 private String userPass=null; //登录密码 private static DButil info = null; private DButil(){} /** * 初始化方法,加载数据库连接信息 * @throws IOException */ private static void init() throws IOException{ Properties prop = new Properties(); prop.load(DButil.class.getResourceAsStream("/db_config.properties")); info = new DButil(); info.driver = prop.getProperty("driver"); info.dbName = prop.getProperty("dbName"); info.host = prop.getProperty("host"); info.point = prop.getProperty("point"); info.userName = prop.getProperty("userName"); info.userPass = prop.getProperty("userPass"); } /** * 得到数据库连接对象 * @return 数据库连接对象 */ static Connection getConn(){ Connection conn=null; if(info == null){ try { init(); } catch (IOException e) { throw new RuntimeException(e.getMessage()); } } if(info!=null){ try { Class.forName(info.driver); String url="jdbc:sqlserver://" + info.host + ":" + info.point + ";databaseName=" + info.dbName; conn=DriverManager.getConnection(url,info.userName,info.userPass); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } } else{ throw new RuntimeException("读取数据库配置信息异常!"); } return conn; } /** * 关闭查询数据库访问对象 * @param rs 结果集 * @param st 上下文 * @param conn 连接对象 */ static void closeConn(ResultSet rs, Statement st,Connection conn){ try { rs.close(); } catch (Exception e) {} try { st.close(); } catch (Exception e) {} try { conn.close(); } catch (Exception e) {} } /** * 关闭增、删、该数据库访问对象 * @param st 上下文对象 * @param conn 连接对象 */ static void closeConn(Statement st ,Connection conn){ try{ st.close(); conn.close(); }catch(Exception e){} } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值