首页 > jdbcTemplate插入MYSQL时怎么返回主键ID

jdbcTemplate插入MYSQL时怎么返回主键ID

    @Override
    public Integer add(Board board) {
        String sql = "INSERT INTO tz_board(title, description) VALUES(?,?)";
        jdbcTemplate.update(sql, board.getTitle(), board.getDescription());
        Integer boardId = jdbcTemplate.
        return boardId;
    }

不知道我这样写对不对

Integer boardId = jdbcTemplate.


Spring提供了一个接口

org.springframework.jdbc.support.KeyHolder

其中有方法

getKey()

方法描述

Retrieve the first map of keys. If there are multiple entries in the list (meaning that multiple rows had keys returned), then an InvalidDataAccessApiUsageException is thrown.


是滴,如楼上所言
org.springframework.jdbc.support.KeyHoldergetKey()方法返回注解,具体看如下例子

http://bailong139.blog.163.com/blog/static/207238100201331383516951/


KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update( new PreparedStatementCreator(){
                    @Override
                   public PreparedStatement createPreparedStatement(Connection conn) throws SQLException{
                        PreparedStatement ps = conn.prepareStatement(SQL_ADD, new String[] {}); 
                        ps = conn.prepareStatement(YOUR_SQL_SCRIPT, Statement.RETURN_GENERATED_KEYS);
                        ps.setString(1, "TEST");
                        ps.setInt(2, 1);
                        //...

                        return ps;
                    }
                },
                keyHolder);
return keyHolder.getKey().intValue();
【热门文章】
【热门文章】