Java框架_Spring5_day06_转账案例(事务)

八、转账案例(添加事务)

8.1 导入坐标,pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.cpz</groupId>
    <artifactId>spring_account</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.8</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.4</version>
        </dependency>
    </dependencies>
</project>

8.2 创建接口 AccountDao.java、AccountService.Dao

AccountDao.java

package com.cpz.dao;

import com.cpz.domain.Account;

public interface AccountDao {

    public Account findByName(String name);

    public void updateAccount(Account account);

}

AccountService.Dao

package com.cpz.service;

public interface AccountService {

    public void transfer(String sourceName,String targetName,Float money);

}

8.3 账户的实体类

package com.cpz.domain;

public class Account {
    private Integer id;
    private String name;
    private Float money;

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Float getMoney() {
        return money;
    }

    public void setMoney(Float money) {
        this.money = money;
    }
}

8.4 ConnectionUtils.java

作用:连接的工具类,它用于数据源中获取一个连接,并且实现和线程的绑定。

package com.cpz.utils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class ConnectionUtils {
    // 让当前线程和Connection绑定
    private ThreadLocal<Connection> tl = new ThreadLocal<Connection>();

    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    // 获取连接对象,并与本地线程绑定
    public Connection getThreadConnection(){
        // 获取线程中的Connection
        Connection connection = tl.get();
        // 线程第一次执行数据操作
        if (connection == null){
            try {
                connection = dataSource.getConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            // 线程绑定
            tl.set(connection);
        }
        return connection;
    }

    // 如果线程结束,解绑
    public void releaseConnection(){
        tl.remove();
    }
}

8.5 TransactionManager.java

作用:和事务管理相关的工具类,包含了开启、提交、回滚事务和释放连接。

package com.cpz.utils;

import java.sql.SQLException;

public class TransactionManager {

    private ConnectionUtils connectionUtils;

    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }

    // 开启事务
    public void beginTransaction(){
        try {
            connectionUtils.getThreadConnection().setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 提交事务
    public void commit(){
        try {
            connectionUtils.getThreadConnection().commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 回滚事务
    public void rollback(){
        try {
            connectionUtils.getThreadConnection().rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 删除事务
    public void close(){
        try {
            connectionUtils.getThreadConnection().close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

8.6 AccountDaoImpl.java

作用:注入连接工具对象,使得操作数据库从同一个连接中获取

package com.cpz.dao.impl;

import com.cpz.dao.AccountDao;
import com.cpz.domain.Account;
import com.cpz.utils.ConnectionUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class AccountDaoImpl implements AccountDao {

    QueryRunner queryRunner;
    ConnectionUtils connectionUtils;

    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }

    public void setQueryRunner(QueryRunner queryRunner) {
        this.queryRunner = queryRunner;
    }

    public Account findByName(String name) {
        try {
            List<Account> list = queryRunner.query(connectionUtils.getThreadConnection(),"select * from account where name = ?", new BeanListHandler<Account>(Account.class), name);
            if (list == null || list.size() == 0){
                return null;
            }else if (list.size() > 1){
                throw new RuntimeException("结果集不唯一,数据有问题!");
            }
            return list.get(0);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public void updateAccount(Account account) {
        try {
            queryRunner.update(connectionUtils.getThreadConnection(),"update account set money = ? where id = ?", account.getMoney(), account.getId());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

8.7 AccountServiceImpl.java

作用:注入事务管理器对象,对每个操作都需要开启事务、提交事务、关闭事务,如果抛出异常,需要回滚事务

package com.cpz.service.impl;

import com.cpz.dao.AccountDao;
import com.cpz.domain.Account;
import com.cpz.service.AccountService;
import com.cpz.utils.TransactionManager;

public class AccountServiceImpl implements AccountService {

    AccountDao accountDao;
    TransactionManager transactionManager;

    public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    public void transfer(String sourceName, String targetName, Float money) {
        try {
            // 开启事务
            transactionManager.beginTransaction();
            // 执行操作
            //1.根据名称查询转出账户
            Account sourceAccount = accountDao.findByName(sourceName);
            //2.根据名称查询转入账户
            Account targetAccount = accountDao.findByName(targetName);
            //3.转出账户减钱
            sourceAccount.setMoney(sourceAccount.getMoney() - money);
            // 设置异常
            int i = 10 / 0;
            //4.转入账户加钱
            targetAccount.setMoney(targetAccount.getMoney() + money);
            //5.更新转出账户
            accountDao.updateAccount(sourceAccount);
            //6.更新转入账户
            accountDao.updateAccount(targetAccount);
            // 提交事务
            transactionManager.commit();
        }catch (Exception e) {
            e.printStackTrace();
            // 回滚操作
            transactionManager.rollback();
        }finally {
            // 释放连接
            transactionManager.close();
        }

    }
}

8.8 ApplicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>

    <bean id="transactionManager" class="com.cpz.utils.TransactionManager">
        <property name="connectionUtils" ref="connectionUtils"></property>
    </bean>

    <bean id="connectionUtils" class="com.cpz.utils.ConnectionUtils">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <bean id="accountService" class="com.cpz.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
        <property name="transactionManager" ref="transactionManager"></property>
    </bean>

    <bean id="accountDao" class="com.cpz.dao.impl.AccountDaoImpl">
        <property name="queryRunner" ref="queryRunner"></property>
        <property name="connectionUtils" ref="connectionUtils"></property>
    </bean>

    <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
        <!--这里要去掉queryRunner的默认连接池配置,由ConnectionUtils 获取连接-->
    </bean>

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driverClass}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

</beans>

8.9 测试类

package com.cpz.test;

import com.cpz.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class SpringTest {

    @Autowired
    AccountService accountService;

    @Test
    public void transfer(){
        accountService.transfer("aaa","bbb",100f);
    }
}

 

这是用Java编写的一个简单的银行转账系统,包括取款,存款,转账等功能,其中用到了数据库的连接,采用Eclipse编写,包含数据库的设计文件。非常适合有一定基础的Java初学者使用。 package com.gujunjia.bank; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.sql.*; /** * * @author gujunjia */ public class DataBase { static Connection conn; static PreparedStatement st; static ResultSet rs; /** * 加载驱动 */ public static void loadDriver() { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.out.println("加载驱动失败"); } } /** * 创建数据库的连接 * * @param database * 需要访问的数据库的名字 */ public static void connectionDatabase(String database) { try { String url = "jdbc:mysql://localhost:3306/" + database; String username = "root"; String password = "gujunjia"; conn = DriverManager.getConnection(url, username, password); } catch (SQLException e) { System.out.println(e.getMessage()); } } /** * 关闭数据库连接 */ public static void closeConnection() { if (rs != null) { // 关闭记录集 try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (st != null) { // 关闭声明 try { st.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { // 关闭连接对象 try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } package com.gujunjia.bank; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * 本类主要实现整个系统的界面 * * @author gujunjia */ public class MainFrame extends JFrame implements ActionListener, FocusListener { /** * */ private static final long serialVersionUID = 1L; public static String userId; JTextField userIdText; JPasswordField passwordText; JButton registerButton; JButton logInButton; public MainFrame() { super("个人银行系统"); this.setSize(400, 500); this.setLocation(getMidDimension(new Dimension(400, 500))); getAppearance(); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } /** * 获取屏幕的中间尺寸 * * @param d * Dimension类型 * @return 一个Point类型的参数 */ public static Point getMidDimension(Dimension d) { Point p = new Point(); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); p.setLocation((dim.width - d.width) / 2, (dim.height - d.height) / 2); return p; } /** * 布局 * * @return Container */ public Container getAppearance() { Container container = this.getContentPane(); container.setLayout(new GridLayout(4, 0)); JLabel label1 = new JLabel("个人银行系统"); label1.setFont(new Font("楷体", Font.BOLD, 40)); JLabel label2 = new JLabel("账号:"); label2.setFont(new Font("楷体", Font.PLAIN, 15)); JLabel label3 = new JLabel("密码:"); label3.setFont(new Font("楷体", Font.PLAIN, 15)); userIdText = new JTextField(20); userIdText.addFocusListener(this); passwordText = new JPasswordField(20); passwordText.addFocusListener(this); JPanel jp1 = new JPanel(); JPanel jp2 = new JPanel(); JPanel jp3 = new JPanel(); JPanel jp4 = new JPanel(); jp1.add(label1); jp2.add(label2); jp2.add(userIdText); jp3.add(label3); jp3.add(passwordText); registerButton = new JButton("注册"); registerButton.addActionListener(this); registerButton.setFont(new Font("楷体", Font.BOLD, 15)); logInButton = new JButton("登录"); logInButton.addActionListener(this); logInButton.setFont(new Font("楷体", Font.BOLD, 15)); jp4.add(registerButton); jp4.add(logInButton); container.add(jp1); container.add(jp2); container.add(jp3); container.add(jp4); return container; } public void actionPerformed(ActionEvent e) { Object btn = e.getSource(); if (btn == registerButton) { new Register(); } else if (btn == logInButton) { String id = userIdText.getText().trim(); String password = new String(passwordText.getPassword()); Bank bank = new Bank(); if (id.equals("") || password.equals("")) { JOptionPane.showMessageDialog(null, "请输入账号和密码"); } else { String dPassword = bank.getPassword(id); if (password.equals(dPassword)) { userId = id; this.dispose(); new UserGUI(); } else { JOptionPane.showMessageDialog(this, "密码或用户名错误", "错误", JOptionPane.ERROR_MESSAGE); } } } } @Override public void focusGained(FocusEvent e) { Object text = e.getSource(); if (text == userIdText) { userIdText.setText(""); userIdText.setFont(new Font("宋体", Font.BOLD, 15)); } else if (text == passwordText) { passwordText.setText(""); } } @Override public void focusLost(FocusEvent e) { Object text = e.getSource(); if (text == userIdText) { if (userIdText.getText().equals("")) { userIdText.setText("请输入账号"); userIdText.setFont(new Font("楷体", Font.ITALIC, 15)); } } } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值