DBUtils控制事务------转账操作

dao:

 

package com.hcx.dao;

import com.hcx.domain.Account;

public interface AccountDao {
	/**
	 * 转账
	 * @param fromname 转出用户
	 * @param toname  转入用户
	 * @param money  转账金额
	 */
	@Deprecated
	public void updateAccount(String fromname,String toname,double money)throws Exception;
	
	/**
	 * 根据账户信息修改金额
	 * @param accout
	 */
	public void updateAccout(Account accout) throws Exception;
	
	/**
	 * 根据用户名查找账户信息
	 * @param name
	 * @return
	 * @throws Exception
	 */
	public Account findAccountByName(String name)throws Exception;
}

 

 

 

dao.impl:

 

package com.hcx.dao.impl;

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

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

import com.hcx.dao.AccountDao;
import com.hcx.domain.Account;
import com.hcx.util.C3P0Util;
import com.hcx.util.ManagerThreadLocal;

public class AccountDaoImpl implements AccountDao {


	public void updateAccount(String fromname, String toname, double money) throws Exception {
		//创建一个QueryRunner对象
		QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
		qr.update("update account set money=money-? where name=?",money,fromname);
		qr.update("update account set money=money+? where name=?",money,toname);
	}

	public void updateAccout(Account account) throws Exception {
		QueryRunner qr = new QueryRunner();
		qr.update(ManagerThreadLocal.getConnection(),"update account set money=? where name=?",account.getMoney(),account.getName());
	}

	public Account findAccountByName(String name) throws Exception {
		QueryRunner qr = new QueryRunner();
		return qr.query(ManagerThreadLocal.getConnection(),"select * from account where name=?", new BeanHandler<Account>(Account.class),name);
	}

}

 

 

 

service:

 

package com.hcx.service;

public interface AccountService {
	/**
	 * 转账
	 * @param fromname 转出用户
	 * @param toname  转入用户
	 * @param money  转账金额
	 */
	public void transfer(String fromname,String toname,double money);
}

 

 

service.impl:

 

package com.hcx.service.impl;

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

import com.hcx.dao.AccountDao;
import com.hcx.dao.impl.AccountDaoImpl;
import com.hcx.domain.Account;
import com.hcx.service.AccountService;
import com.hcx.util.C3P0Util;
import com.hcx.util.ManagerThreadLocal;

public class AccountServiceImpl implements AccountService {

	public void transfer(String fromname, String toname, double money) {
	//	ad.updateAccount(fromname, toname, money);
		AccountDao ad = new AccountDaoImpl();
		
		try {
			ManagerThreadLocal.startTransacation();//begin
			//分别得到转出和转入账户对象
			Account fromAccount = ad.findAccountByName(fromname);
			Account toAccount = ad.findAccountByName(toname);
			
			//修改账户各自的金额
			fromAccount.setMoney(fromAccount.getMoney()-money);
			toAccount.setMoney(toAccount.getMoney()+money);
			
			//完成转账操作
			ad.updateAccout(fromAccount);
//			int i = 10/0;
			ad.updateAccout(toAccount);
			
			ManagerThreadLocal.commit();//提交事务
		} catch (Exception e) {
			try {
				ManagerThreadLocal.rollback();//回滚事务
			} catch (Exception e1) {
				e1.printStackTrace();
			} 
		}finally{
			try {
				ManagerThreadLocal.close();
			} catch (Exception e) {
				e.printStackTrace();
			}//关闭
		}
	}

}

 

 

 

domain:

 

package com.hcx.domain;

public class Account {
	private int id;
	private String name;
	private double money;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getMoney() {
		return money;
	}
	public void setMoney(double money) {
		this.money = money;
	}
	@Override
	public String toString() {
		return "Account [id=" + id + ", name=" + name + ", money=" + money
				+ "]";
	}
	
	
}

 

 

 

util:

C3P0Util:

package com.hcx.util;

import java.beans.PropertyVetoException;
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;

public class C3P0Util {
	//得到一个数据源
	private static DataSource dataSource = new ComboPooledDataSource();
	
	
	public static DataSource getDataSource() {
		return dataSource;
	}

	//从数据源中得到一个连接对象
	public static Connection getConnection(){
		try {
			return dataSource.getConnection();
		} catch (SQLException e) {
			throw new RuntimeException("服务器错误");
		}
	}
	
	public static void release(Connection conn,Statement stmt,ResultSet rs){
		//关闭资源
				if(rs!=null){
					try {
						rs.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
					rs = null;
				}
				if(stmt!=null){
					try {
						stmt.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
					stmt = null;
				}
				if(conn!=null){
					try {
						conn.close();//关闭
					} catch (Exception e) {
						e.printStackTrace();
					}
					conn = null;
				}
	}
	
}

 

ManagerThreadLocal:

 

package com.hcx.util;

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

public class ManagerThreadLocal {
	private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
	
	//得到一个连接
	public static Connection getConnection(){
		Connection conn = tl.get();//从当前线程中取出一个连接
		if(conn==null){
			conn = C3P0Util.getConnection();//从池中取出一个
			tl.set(conn);//把conn对象放入到当前线程对象中
		}
		return conn;
	}
	
	//开始事务
	public static void startTransacation(){
		try {
			Connection conn = getConnection();
			conn.setAutoCommit(false);//从当前线程对象中取出的连接,并开始事务
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public static void commit(){
		try {
			getConnection().commit();//提交事务
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public static void rollback(){
		try {
			getConnection().rollback();//回滚事务
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public static void close(){
		try {
			getConnection().close();//把连接放回池中
			tl.remove();//把当前线程对象中的conn移除
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

 

 

 

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://localhost:3306/day13</property>
	<property name="user">root</property>
	<property name="password">abc</property>
    <property name="initialPoolSize">10</property>
    <property name="maxIdleTime">30</property>
    <property name="maxPoolSize">100</property>
    <property name="minPoolSize">10</property>

  </default-config>

</c3p0-config>

 

 

 

commons-dbutils-1.7 jar是Apache Commons项目中的一个Java库,主要用于简化和优化数据库操作。该jar包提供了一组实用工具类,可以减少编写JDBC代码的工作量,同时提供了一种简单而强大的方式来处理数据库连接和查询。 commons-dbutils-1.7 jar主要包括以下几个核心类和接口: 1. QueryRunner:用于执行SQL语句,提供了一系列的查询方法,可以方便地执行查询操作并返回结果。 2. ResultSetHandler:用于处理SQL查询结果集,提供了多种实现类如BeanHandler、BeanListHandler、ScalarHandler等,方便处理不同类型的查询结果。 3. ResultSetExtractor:用于提取结果集中的数据,可以通过自定义的方式从结果集中获取数据并进行处理。 4. BatchExecutor:用于执行批量SQL语句,可以一次性执行多个SQL语句,提高数据库操作的效率。 通过使用commons-dbutils-1.7 jar,可以简化数据库操作代码的编写过程,减少重复劳动。它隐藏了许多JDBC的细节,提供了一种更高级别的抽象,使开发者可以更加专注于业务逻辑的实现,而不是过多关注数据库操作的细节。 另外,commons-dbutils-1.7 jar还具备良好的可扩展性和灵活性,可以与其他开源框架(如Spring、Hibernate)和数据库(如MySQL、Oracle)无缝集成,以满足不同项目的需求。 总之,commons-dbutils-1.7 jar是一个功能强大且易于使用的Java库,可以简化和优化数据库操作,提高开发效率和代码质量。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值