首页 > 代码库 > springmvc的jdbcTemplate 插入 返回主键

springmvc的jdbcTemplate 插入 返回主键

    public int insertCustomer(final Customer customer) {
        //TODO.
        final String sql = "insert into customer (mobile,nickname,password,score,avatar,push_key,reg_time) values(?,?,?,?,?,?,now())";
        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
                PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                ps.setString(1, customer.getMobile());
                ps.setString(2, customer.getNickname());
                ps.setString(3, customer.getPassword());
                ps.setInt(4, customer.getScore());
                ps.setString(5, customer.getAvatar());
                ps.setString(6,customer.getPushKey());
               // ps.setString(7, customer.getRegTime());
                return ps;
            }
        }, keyHolder);
        return keyHolder.getKey().intValue();
    }

springmvc的jdbcTemplate 插入 返回主键