注意:使用JdbcTemplate之前需要导入Spring框架的jar包以及一些依赖包,简单方法是在Eclipse中 项目->右键->Myeclipse->
Add Spring...
基于JdbcTemplate的UserDao接口实现:
public class UserDaoSpringImpl implements UserDao {
private SimpleJdbcTemplate simpleJdbcTemplate = new SimpleJdbcTemplate(JdbcUtils.getMyDataSource());
@Override
public void addUser(User user) {
String sql = "insert into user(name,password,birthday,money) values(:name,:password,:birthday,:money)";
SqlParameterSource paramSource = new BeanPropertySqlParameterSource(user);
KeyHolder keyHolder = new GeneratedKeyHolder();
this.simpleJdbcTemplate.getNamedParameterJdbcOperations().update(sql, paramSource, keyHolder);
user.setId(keyHolder.getKey().longValue()); // 获取生成主键
}
@Override
public void delete(User user) {
String sql = "delete from user where id=?";
Object[] args = new Object[] { user.getId() };
this.simpleJdbcTemplate.update(sql, args);
}
@Override
public User findUser(String loginName, String password) {
String sql = "select name,password,birthday,money from user where name=? and password=?";
Object[] args = new Object[] { loginName, password };
User user = (User) this.simpleJdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), args);
return user;
}
@Override
public User getUser(int userId) {
String sql = "select id,name,password,birthday,money from user where id=?";
Object[] args = new Object[] { userId };
User user = (User) this.simpleJdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), args);
return user;
}
@Override
public String getUserName(int id) {
String sql = "select name from user where id=?";
String name = (String) this.simpleJdbcTemplate.queryForObject(sql, String.class, id);
return name;
}
@Override
public void update(User user) {
String sql = "update user set name=:name,password=:password,birthday:=birthday,money=:money where id=:id";
SqlParameterSource paramterSource = new BeanPropertySqlParameterSource(user);
this.simpleJdbcTemplate.update(sql, paramterSource);
}
@Override
public List<User> getUsers(int id) {
String sql = "select id,name,password,birthday,money from user where id<?";
List<User> users = (List<User>) this.simpleJdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class), id);
return users;
}
}