AccountServiceImpl accountService=new AccountServiceImpl();
//实例化业务层对象,调取业务层方法
int res=accountService.transfor("10086","123","10010",100.5);
System.out.println("转账"+res);
2.业务层
public int transfor(String toAccount, String password, String fromAccount, double money) {
AccountDaoImpl accountDao=new AccountDaoImpl();
Account toAcc=accountDao.selectCart(toAccount);//1.首先判断发款方与收款方账户是否存在
Account fromAcc=accountDao.selectCart(fromAccount);
if (toAcc.getCart()==null){//i.查询转账方账户是否存在
throw new RuntimeException("转账方账户不存在");
}
if (!toAcc.getPassword().equals(password)){//ii.查询转账方账户密码是否正确
throw new RuntimeException("转账方密码不正确");
}
if (toAcc.getMoney()<money){//iii.查看转账方账户余额是否充足
throw new RuntimeException("账户余额不足");
}
if (fromAcc.getCart()==null){//iv.查看收款方账户是否存在
throw new RuntimeException("收款方账户不存在");
}
Connection conn=null;
int res=0;
try {
DruidBUtils.begin();
toAcc.setMoney(toAcc.getMoney()-money);//v.完成转账方发钱与收款收账方的收款功能,并返回转账是否有效给测试层
res=accountDao.update(toAcc);//2.更新账余额,返回给前端
int i=1/0;
fromAcc.setMoney(fromAcc.getMoney()+money);
res=accountDao.update(fromAcc);
DruidBUtils.commit();
} catch (Exception e) {
System.out.println("事务的回滚");
try {
DruidBUtils.rollback();
} catch (Exception ex) { ex.printStackTrace(); }
}
return res;
}
3.Dao层即数据访问层
public Account selectCart(String toAccount) {
String sql="select * from account where cart=?";
List<Account> list=DaoUtils.commonsQuery(sql,Account.class,toAccount);
if (list.size()>0){
return list.get(0);
}
return null;
}
public int update(Account toAcc) {
String sql="update account set money=? where cart=?";
return DaoUtils.commonsUpdate(sql,toAcc.getMoney(),toAcc.getCart());
}