Getting auto-generated key from row insertion in spring 3 / PostgreSQL 8.4.9

后端 未结 9 1265
北荒
北荒 2020-12-04 17:40

I would like to retrieve the auto-generated id from a row insertion, but I get a NullPointerException

Here is the code :

long result = 0         


        
相关标签:
9条回答
  • 2020-12-04 18:25

    I had the same problem and it turned out that my table ID was not auto incrementing.

    0 讨论(0)
  • 2020-12-04 18:31

    Take a look at this post, especially the accepted answer of using the INSERT...RETURNING syntax:

    How to get a value from the last inserted row?

    This the best way to get this value in PostgreSQL as you only make one network round trip and it's done as a single atomic operation on the server.

    0 讨论(0)
  • 2020-12-04 18:33
    KeyHolder holder = new GeneratedKeyHolder();
    
    getJdbcTemplate().update(new PreparedStatementCreator() {           
    
                    @Override
                    public PreparedStatement createPreparedStatement(Connection connection)
                            throws SQLException {
                        PreparedStatement ps = connection.prepareStatement(sql.toString(),
                            Statement.RETURN_GENERATED_KEYS); 
                        ps.setString(1, person.getUsername());
                        ps.setString(2, person.getPassword());
                        ps.setString(3, person.getEmail());
                        ps.setLong(4, person.getRole().getId());
                        return ps;
                    }
                }, holder);
    
    Long newPersonId = holder.getKey().longValue();
    

    Note that in newer versions of Postgres you need to use

    connection.prepareStatement(sql.toString(), 
        new String[] { "idcompte" /* name of your id column */ })
    

    instead of

    connection.prepareStatement(sql.toString(), 
        Statement.RETURN_GENERATED_KEYS);
    
    0 讨论(0)
提交回复
热议问题