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

后端 未结 9 1264
北荒
北荒 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:09
    setGeneratedKeysColumnNames(new String[]{"column_name"});
    

    Don't forget to set the names for the auto-generated columns.

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

    I faced the similar problem. I do not know why exactly I faced this problem but good thing is I got to resolve this by using below code:

    final KeyHolder holder = new GeneratedKeyHolder();
    int status = myTemplate.update(yourInsertSQL, namedParameters, holder, new String[]{"PrimaryKeyColumnName"});
    

    Hope that helps someone.

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

    A solution using NamedParameterJdbcTemplate with Sequence.nextval :

            MapSqlParameterSource parameters = new MapSqlParameterSource();
            parameters.addValue("prenom", prenom);
            parameters.addValue("nom", nom);
            parameters.addValue("datenaissance", datenaissance);
            parameters.addValue("numtelephone", numtelephone);
    
        final String SQL = "INSERT INTO compte (idcompte,  prenom, nom, datenaissance, numtelephone) "
                            + " VALUES(compte_idcompte_seq.NEXTVAL, :prenom, :nom, :datenaissance, :numtelephone)";
    
            KeyHolder keyHolder = new GeneratedKeyHolder();
            NamedParameterJdbcTemplate namedJdbcTemplate = new NamedParameterJdbcTemplate(txManager.getDataSource());
            int nb = namedJdbcTemplate.update(SQL, parameters, keyHolder, new String[]{"idcompte"});
            Long generatedId = keyHolder.getKey().longValue();
    

    I like this solution because with NamedParameterJdbcTemplate because the parameters are passed by name and the code is more readable and less prone to errors, especially when there are big queries.

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

    The easiest way to get a key back from an INSERT with Spring JDBC is to use the SimpleJdbcInsert class. You can see an example in the Spring Reference Guide, in the section titled Retrieving auto-generated keys using SimpleJdbcInsert.

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

    There seems to be some known issues with Keyholder and PostgreSQL. Have a look at the workaround at this link Spring JDBC - Last inserted id

    Also do check the database table directly to see if the record is inserted properly(i.e with PK). This will help to narrow down the problem.

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

    I'm using Spring3.1 + PostgreSQL9.1, and when I use this

        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection connection)
                    throws SQLException {
                PreparedStatement ps = 
                    connection.prepareStatement(youSQL, 
                        Statement.RETURN_GENERATED_KEYS);
                ps.setString(1, post.name_author);
                ...
                return ps;
            }
        }, keyHolder);
        long id = keyHolder.getKey().longValue();
    

    I got this exception:

     org.springframework.dao.InvalidDataAccessApiUsageException: 
    The getKey method should only be used when a single key is returned.  
    The current key entry contains multiple keys: ...
    

    So I changed to :

    PreparedStatement ps = 
    connection.prepareStatement(youSQL, new String[]{"id"});
    

    where "id" is

    id serial not null primary key
    

    And the problem is solved. So I supposed that using

    prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
    

    is not right here. The official guide is here, Chapter 13.2.8 :Retrieving auto-generated keys

    0 讨论(0)
提交回复
热议问题