public interface AccountDao { public void addAccount(int id, double account); public void inAccount(int id, double account); public void outAccount(int id, double account); }
存款访问实现类(AccountDaoImpl):实现接口(AccountDao)定义的方法。
public class AccountDaoImpl implements AccountDao{ private JdbcTemplate jdbcTemplate; public void setJdbcTemplate(JdbcTemplate jdbc){ this.jdbcTemplate = jdbc; } @Override public void addAccount(int id, double account) { // TODO Auto-generated method stub String sql = "insert into account values(" + id + "," + account + ")"; this.jdbcTemplate.execute(sql); } @Override public void inAccount(int id, double account) { // TODO Auto-generated method stub String sql = "update account set account=account+? where userid=?"; this.jdbcTemplate.update(sql, account,id); } @Override public void outAccount(int id, double account) { // TODO Auto-generated method stub String sql = "update account set account=account-? where userid=?"; this.jdbcTemplate.update(sql, account,id); } } View Code
存款服务层方法接口(AccountService):定义暴露对外的,提供给用户访问的接口。
public interface AccountService { /* * 转账,实现从outUser转出account金额的钱到inUser */ public void transfer(User outUser, User inUser, double account); }
存款服务层方法实现类(AccountServiceImpl):实现接口(AccountService)中定义的方法。
public class AccountServiceImpl implements AccountService{ private AccountDao accountDao; public void setAccountDao(AccountDao accountDao) { this.accountDao = accountDao; } @Override public void transfer(User outUser, User inUser, double account){ // TODO Auto-generated method stub this.accountDao.outAccount(outUser.getUserID(), account); //模拟程序异常,无法执行inAccount方法 int i = 1 / 0; this.accountDao.inAccount(inUser.getUserID(), account); } } View Code
创建数据库表的类(CreateTables)
public class CreateTables { //通过JdbcTemplate对象创建表 private JdbcTemplate jdbcTemplate; public void setJdbcTemplate(JdbcTemplate jdbc){ jdbcTemplate = jdbc; } public void createTable(String sql){ jdbcTemplate.execute(sql); } } View Code
客户端类(Client)如下: