java事务操作

DataSourceUtil:

public class DataSourceUtil {

	// 使用默认配置(c3p0-config.xml--default-config)
	private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
	// 创建ThreadLocal
	private static ThreadLocal<Connection> t = new ThreadLocal<Connection>();

	/**
	 * 获得数据源
	 * 
	 * @return
	 */
	public static DataSource getDateSource() {
		return dataSource;

	}

	/**
	 * 获取Conection
	 * 
	 * @return
	 */
	public static Connection getConnection() {
		Connection conn = null;
		try {
			conn = dataSource.getConnection();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return conn;
	}

	/**
	 * 获取和线程绑定的Connection
	 */
	public static Connection getCurrentConnection() {
		Connection conn = t.get();
		if (conn == null) {
			conn = getConnection();
		}
		t.set(conn);

		return conn;
	}

	/**
	 * 开启事务
	 * 
	 * @throws SQLException
	 */
	public static void startTransction() throws SQLException {
		getCurrentConnection().setAutoCommit(false);
	}

	/**
	 * 回滚事务
	 * 
	 * @throws SQLException
	 */
	public static void rollBack() throws SQLException {
		getCurrentConnection().rollback();
	}

	/**
	 * 提交事务
	 * 
	 * @throws SQLException
	 */
	public static void commit() throws SQLException {
		getCurrentConnection().commit();
		// 从ThreadLocal总移除Connection
		t.remove();
		getCurrentConnection().close();
	}

}
TransforDao:

public class TransforDao {
	/**
	 * 出账操作
	 * @param out
	 * @param money
	 * @throws SQLException
	 */
	public void out(String out, double money) throws SQLException {
		QueryRunner runner = new QueryRunner();
		Connection conn = DataSourceUtil.getCurrentConnection();
		String sql = "update account set money=money-? where name=?";
		Object[] params = { money, out };
		runner.update(conn, sql, params);
	}
	/**
	 * 入账操作
	 * @param in
	 * @param money
	 * @throws SQLException
	 */
	public void in(String in, double money) throws SQLException {
		QueryRunner runner = new QueryRunner();
		Connection conn = DataSourceUtil.getCurrentConnection();
		String sql = "update account set money=money+? where name=?";
		Object[] params = { money, in };
		runner.update(conn, sql, params);
	}

}
TransforService:

public class TransforService {

	public boolean transforMoney(String out, String in, double money) {
		boolean flag=true;
		
		TransforDao dao=new TransforDao();
		
		try {
			//开启事务
			DataSourceUtil.startTransction();
			dao.out(out, money);
			dao.in(in, money);
		} catch (SQLException e) {
			e.printStackTrace();
			flag=false;
			try {
				//回滚事务
				DataSourceUtil.rollBack();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		finally {
			try {
				//提交事务
				DataSourceUtil.commit();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		
		return flag;
	}

}




猜你喜欢

转载自blog.csdn.net/qq_33371372/article/details/79152741