日期:2014-05-16 浏览次数:20487 次
package cn.com.spring; import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper; import org.springframework.jdbc.core.simple.ParameterizedRowMapper; import org.springframework.jdbc.core.simple.SimpleJdbcTemplate; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import cn.com.JDBC.JdbcUtils; import cn.com.dao.UserDao; import cn.com.jadbc.domain.User; public class UserDaoSpringImpl implements UserDao { private SimpleJdbcTemplate simplejdbcTemplate=new SimpleJdbcTemplate(JdbcUtils.getDataSource()); @Override public void addUser(User user) { // TODO Auto-generated method stub String sql="insert into user(name,money,birthday)values(:name,:money,:birthday)"; SqlParameterSource param=new BeanPropertySqlParameterSource(user); KeyHolder keyHolder=new GeneratedKeyHolder(); this.simplejdbcTemplate.getNamedParameterJdbcOperations().update(sql, param, keyHolder); user.setId(keyHolder.getKey().intValue()); } @Override public User findUser(String loginName, String password) { String sql="select id,name,money,birthday from user where name=?"; return this.simplejdbcTemplate.queryForObject(sql, ParameterizedBeanPropertyRowMapper.newInstance(User.class), loginName); } @Override public User getUser(int userId) { String sql="select id,name,money,birthday from user where id=?"; return this.simplejdbcTemplate.queryForObject(sql, ParameterizedBeanPropertyRowMapper.newInstance(User.class), loginName); } @Override public void update(User user) { String sql="update user set name=?,birthday=?,money=? where id=?"; this.simplejdbcTemplate.update(sql, user.getName(),user.getId(),user.getBirthday(),user.getMoney()); //方法二: String sql="update user set name=:name,birthday=:birthday,money=:money where id=:id"; this.simplejdbcTemplate.update(sql, new BeanPropertySqlParameterSource(user)); } @Override public void delete(User user) { // TODO Auto-generated method stub String sql="delete from user where id=?"; this.simplejdbcTemplate.update(sql, user.getId()); } } package cn.com.dao; import cn.com.jadbc.domain.User; public interface UserDao { public void addUser(User user); public User findUser(String loginName,String password); public User getUser(int userId); public void update(User user); public void delete(User user); }