JAVA JDBC SQL 回滚事务

\src\com\by\util\JDBCUtils.java

package com.by.util;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * JDBCTemplate工具类
 */
public class JDBCUtils {
    private static final DataSource dataSource;
    static {
        Properties p = new Properties();  //创建集合
        try (   //FileInputStream fis=new FileInputStream("src/JDBCUtils.properties")
                InputStream is=JDBCUtils.class.getResourceAsStream("/JDBCUtils.properties")  //将文件路径与项目结构脱离
             ) {
            p.load(is); //利用IO流将配置文件的内容读取到集合中
        } catch (Exception e) {
            System.out.println("未知异常!");
            e.printStackTrace();
        }
        dataSource = new DriverManagerDataSource(p.getProperty("url"), p.getProperty("username"), p.getProperty("password"));
    }

    /**
     * 获取JDBCTemplate对象
     * @return JDBCTemplate对象
     */
    public static JdbcTemplate getJDBCTemplate(){
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);  //创建JDBCTemplate
        return jdbcTemplate;
    }

    /**
     * 获取数据库连接池对象
     * @return
     */
    public static DataSource getDataSource(){
        return dataSource;
    }

    /**
     * 获取连接,开启事务
     * @return
     */
    public static Connection startTransaction(){
        if (!TransactionSynchronizationManager.isSynchronizationActive()) { //判断是否开启了线程绑定
            TransactionSynchronizationManager.initSynchronization();  //开启线程绑定
        }

        Connection conn = DataSourceUtils.getConnection(dataSource);
        try {
            conn.setAutoCommit(false);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return conn;
    }

    /**
     * 提交事务
     * @param conn 用来提交事务的数据库连接
     */
    public static void commit(Connection conn){
        try {conn.commit();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally{clear(conn);}
    }

    /**
     * 回滚事务
     * @param conn
     */
    public static void rollback(Connection conn){
        try {conn.rollback();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally{clear(conn);}
    }

    public static void clear(Connection conn){
        TransactionSynchronizationManager.clear();   //清理资源
        TransactionSynchronizationManager.unbindResourceIfPossible(dataSource);  //解除绑定
        if(conn!=null){  //归还连接
            DataSourceUtils.releaseConnection(conn,dataSource);
        }
    }
}

\src\com\by\service\AccountService.java

package com.by.service;

public interface AccountService {
    /**
     * 转账功能
     * @param fromName 转出人姓名
     * @param toName 转入人姓名
     * @param money 转账金额
     * @return 转账结果
     */
    boolean transfer(String fromName, String toName, double money);
}

\src\com\by\service\impl\AccountServiceImpl.java

package com.by.service.impl;

import com.by.dao.AccountDao;
import com.by.dao.impl.AccountDaoImpl;
import com.by.entity.Account;
import com.by.service.AccountService;
import com.by.util.JDBCUtils;
import org.springframework.jdbc.datasource.DataSourceUtils;

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

public class AccountServiceImpl implements AccountService {
    private AccountDao ad = new AccountDaoImpl();
    @Override
    public boolean transfer(String fromName, String toName, double money) {
        boolean boo=false;//用来返回
        Connection conn=null;
        try{
            //开启事务
            conn = JDBCUtils.startTransaction();
            //功能实现: 调用DAO+逻辑控制
            //判断转出人是否存在
            Account from = ad.selectAccountByUsername(fromName);
            //判断转出人是否存在
            if (from == null) {
                throw new RuntimeException("转出人不存在!");
            } else {
                //判断余额
                if (from.getBalance() < money) {
                    throw new RuntimeException("余额不足");
                } else {
                    //查询转入人
                    Account to = ad.selectAccountByUsername(toName);
                    if (to == null) {
                        throw new RuntimeException("转入人不存在");
                    } else {
                        //执行转账
                        int n = ad.updateAccountByUsername(new Account(null, fromName, null, from.getBalance() - money));
                        if (true) {
                            throw new RuntimeException("这是我的测试异常");
                        }
                        n += ad.updateAccountByUsername(new Account(null, toName, null, to.getBalance() + money));
                        if (n == 2) {
                            boo= true;
                        }
                    }
                }
            }
            JDBCUtils.commit(conn);  //提交事务
        }catch(Exception e){
            try{ //回滚事务
                System.out.println("事务正在回滚。。。");
                JDBCUtils.rollback(conn);
            }catch(RuntimeException ex){
                throw ex;
            }
            throw new RuntimeException(e);
        }
        return boo;

    }
}

\src\com\by\view\view3\UpdateAccountTest.java

package com.by.view.view3;

import com.by.service.AccountService;
import com.by.service.impl.AccountServiceImpl;

import java.util.Scanner;

public class UpdateAccountTest {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        //接收转出人的账号名
        System.out.println("请输入转出人账号名:");
        String fromName = sc.next();
        System.out.println("请输入转账金额:");
        double money = sc.nextDouble();
        //存在,接收转入人账号名
        System.out.println("请输入转入人姓名:");
        String toName = sc.next();

        //创建业务层对象
        AccountService as = new AccountServiceImpl();
        try {
            if (as.transfer(fromName, toName, money)) {
                System.out.println("转账成功");
            } else {
                System.out.println("转账失败");
            }
        } catch (Exception e) {
            System.out.println("转账失败!原因为:"+e.getMessage());
        }
    }
}

你可能感兴趣的:(java,sql,python)