您的位置:首页 > 其它

银行转账业务-使用事务

2017-08-13 20:25 375 查看
银行转账是是两个账户之间同时进行操作的,一方账户资金减少的同时另外一方的资金就要增加同样的金额。如果一方操作失败那么另外一方的操作就不会成功。也即是需要将这样的两个操作放在一个事务当中。只是这里使用到了层的概念。既然设计到转账那么肯定有一个账户类(DTO数据传输对象),还有一个类是专门用来访问该账户的(DAO数据访问对象)。而我们所需要进行的转账操作则是可以放在服务层进行处理(service)。

DTO(数据传输对象)

public class Account {
private int id;
private String account;
private double cash;
public Account() {
}
public Account(String account, double cash) {
super();
this.account = account;
this.cash = cash;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public double getCash() {
return cash;
}
public void setCash(double cash) {
this.cash = cash;
}

}


DAO(数据访问对象)

public class AccountDAO implements BaseDAO<Account> {

private Connection conn;

public AccountDAO(Connection conn) {
this.conn = conn;
}

@Override
public boolean insert(Account t) {
return false;
}

@Override
public boolean delete(Account t) {
return false;
}

@Override
public boolean update(Account t) {
return DAOHelper.execUpdate(conn,
"update tbaccount set cash = ? where account = ?", t.getCash(), t.getAccount());
}

@Override
public Account findById(final Account t) {
return DAOHelper.queryOne("select * from tbaccount where id = ?",
new CallBack<Account>() {
@Override
public Account getData(ResultSet rs) {
try {
if (rs.next()) {
t.setAccount(rs.getString("account"));
t.setCash(rs.getDouble("cash"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return t;
}
}, t.getId());
}

@Override
public List<Account> findAll() {
return null;
}

}


service层

public class AccountService extends BaseConn {

// 事务
public void transfAccount(Account a, Account b, double money) {
Connection conn = getConn();
// 分别查询出A,B账号的个子金额
AccountDAO dao = new AccountDAO(conn);
a = dao.findById(a);
b = dao.findById(b);
if ((a.getAccount() != null) && (b.getAccount() != null)) {
// 判断账号a余额是否足够
if (a.getCash() >= money) {
// 减少A账号的余额
a.setCash(a.getCash() - money);
// 增加B账号的余额
b.setCash(b.getCash() + money);
try {
// 关闭事务自动提交
conn.setAutoCommit(false);
// 开始转账(这里有问题)
boolean f1 = dao.update(a);
boolean f2 = dao.update(b);
if (f1 && f2) {
conn.commit();
System.out.println("转账成功!");
}
} catch (SQLException e) {
try {
conn.rollback();
System.out.println("转账失败");
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}

} else {
System.out.println("余额不足!");
}
}else {
System.out.println("账号A或者B不存在!");
}
}

public static void main(String[] args) {
Account a = new Account();
Account b = new Account();
a.setId(1);
b.setId(3);
new AccountService().transfAccount(a, b, 1000);
}
}


当然这里使用了一些工具类,比如连接数据库的类。但是主要的操作是上面的三个类。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐