• JDBC 使用SimpleJdbcTemplate实现Dao


    public interface UserDao {
        public void addUser(User user);

        public User getUser(int userId);

        public User findUser(String loginName, String password);

        public void update(User user);

        public void delete(User user);

    }

     

     

     

     

    public class UserDaoSpringImpl implements UserDao {
        private SimpleJdbcTemplate simpleJdbcTemplate = new SimpleJdbcTemplate(
                JdbcUtils.getDataSource());

        public void addUser(User user) {
            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());
        }

        public void delete(User user) {
            String sql = "delete from user where id=?";
            this.simpleJdbcTemplate.update(sql, user.getId());
        }

        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);
        }

        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),
                    userId);
        }

        public void update(User user) {
            String sql = "update user set name=?, birthday=?, money=? where id=? ";
            this.simpleJdbcTemplate.update(sql, user.getName(), user.getBirthday(),
                    user.getMoney(), user.getId());

            sql = "update user set name=:name, birthday=:birthday, money=:money where id=:id ";
            this.simpleJdbcTemplate.update(sql, new BeanPropertySqlParameterSource(
                    user));
        }

    }

  • 相关阅读:
    Java 重写(Override)与重载(Overload)
    Java 继承
    Java 异常处理
    Java Scanner 类
    Java 流(Stream)、文件(File)和IO
    Java 方法
    Java 正则表达式
    Beta冲刺——代码规范、冲刺任务与计划
    Beta冲刺——凡事预则立
    Beta冲刺——问题总结博客(事后诸葛亮和组员交换事宜)
  • 原文地址:https://www.cnblogs.com/flying607/p/3467037.html
Copyright © 2020-2023  润新知