public class User { private int userID; //用户ID private String userName; //用户名 private String passwd; //用户密码 public int getUserID() { return userID; } public void setUserID(int userID) { this.userID = userID; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPasswd() { return passwd; } public void setPasswd(String passwd) { this.passwd = passwd; } } /* *用户工厂类负责创建User对象 */ public class UserFactory { public User createUser(String name, int id, String password){ User user = new User(); user.setUserName(name); user.setUserID(id); user.setPasswd(password); return user; } }
接下来创建UserDao接口,负责定义对User数据的操作,实现对User的增加、修改和删除操作,然后定义具体的实现类UserDaoImpl类,代码如下:
/* *定义对User对象的操作 */ public interface UserDao { public int addUser(User user); public int updateUser(User user); public int deleteUser(User user); } /* * UserDao接口的具体实现类 */ public class UserDaoImpl implements UserDao{ private JdbcTemplate jdbcTemplate; public void setJdbcTemplate(JdbcTemplate jdbc){ this.jdbcTemplate = jdbc; } @Override public int addUser(User user) { // TODO Auto-generated method stub String sql = "insert into t_user(userid,username,password)values(?,?,?)"; Object[] obj = new Object[]{ user.getUserID(), user.getUserName(), user.getPasswd() }; return this.execute(sql, obj); } @Override public int updateUser(User user) { // TODO Auto-generated method stub String sql = "update t_user set username=?,password=? where userid=?"; Object[] obj = new Object[]{ user.getUserName(), user.getPasswd(), user.getUserID() }; return this.execute(sql, obj); } @Override public int deleteUser(User user) { // TODO Auto-generated method stub String sql = "delete from t_user where userid=?"; Object[] obj = new Object[]{ user.getUserID() }; return this.execute(sql, obj); } //负责SQL语句的执行 private int execute(String sql, Object[] obj){ return this.jdbcTemplate.update(sql, obj); } }