在Spring 3 / PostgreSQL 8.4.9中从行插入中获取自动生成的密钥

问题描述 投票:44回答:9

我想从行插入中检索自动生成的id,但我得到了NullPointerException

这是代码:

long result = 0;
        final String SQL = "INSERT INTO compte (prenom, nom, datenaissance, numtelephone) "
                            + " VALUES(?,?,?,?)";
        KeyHolder keyHolder = new GeneratedKeyHolder();
        int row= this.jdbcTemplate.update(new PreparedStatementCreator(){
            public PreparedStatement createPreparedStatement(Connection connection)
                throws SQLException {
                PreparedStatement ps =connection.prepareStatement(SQL);
                ps.setString(1, a.getSurname());
                ps.setString(2, a.getName());
                ps.setDate(3, a.getDob());
                ps.setString(4, a.getPhone());
                return ps;
            }
        },keyHolder);

        if (row > 0)
            result = keyHolder.getKey().longValue(); //line 72

这是PostgreSQL表:

CREATE TABLE compte
(
  idcompte serial NOT NULL,
  prenom character varying(25) NOT NULL,
  nom character varying(25) NOT NULL,
  datenaissance date NOT NULL,
  numtelephone character varying(15) NOT NULL,
  CONSTRAINT pk_compte PRIMARY KEY (idcompte )
);

PostgreSQL支持自动生成的密钥,但是我得到了这个异常:

java.lang.NullPointerException
    at com.tante.db.JDBCUserAccountDAO.insertAccount(JDBCUserAccountDAO.java:72)

编辑:我试过这个来获取自动生成的密钥:

result = jdbcTemplate.queryForLong("select currval('compte_idcompte_seq')");

但我得到一个PSQLException

the current value (currval) of the sequence compte_idcompte_seq is not defined in this session,虽然我认为在插入行时应该调用compte_idcompte_seq.NEXTVAL

编辑:

插入行时,会正确创建自动增量值

任何的想法 ?

java spring postgresql jdbc auto-generate
9个回答
59
投票
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();

请注意,在较新版本的Postgres中,您需要使用

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

代替

connection.prepareStatement(sql.toString(), 
    Statement.RETURN_GENERATED_KEYS);

22
投票

使用Spring JDBC从INSERT获取密钥的最简单方法是使用SimpleJdbcInsert类。您可以在Spring参考指南的Retrieving auto-generated keys using SimpleJdbcInsert部分中看到一个示例。


12
投票

我正在使用Spring 3.1 + PostgreSQL 9.1,当我使用它时

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

我有这个例外:

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

所以我改为:

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

其中“id”是

id serial not null primary key

问题解决了。所以我认为使用

prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

不在这里官方指南是here,第13.2.8节:检索自动生成的密钥


5
投票

使用NamedParameterJdbcTemplate和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();

我喜欢这个解决方案,因为使用NamedParameterJdbcTemplate,因为参数是按名称传递的,代码更易读,更不容易出错,尤其是在有大查询时。


1
投票

Keyholder和PostgreSQL似乎存在一些已知问题。看看这个链接Spring JDBC - Last inserted id的解决方法

还要直接检查数据库表以查看是否正确插入了记录(即使用PK)。这将有助于缩小问题范围。


1
投票

看一下这篇文章,特别是使用INSERT ... RETURNING语法的已接受答案:

How to get a value from the last inserted row?

这是在PostgreSQL中获取此值的最佳方法,因为您只进行一次网络往返,并且它在服务器上作为单个原子操作完成。


1
投票

我遇到了同样的问题,原来我的表ID没有自动递增。


1
投票

我遇到了类似的问题。我不知道为什么我会遇到这个问题,但好的是我必须通过使用下面的代码来解决这个问题:

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

希望能帮助别人。


0
投票
setGeneratedKeysColumnNames(new String[]{"column_name"});

不要忘记为自动生成的列设置名称。

© www.soinside.com 2019 - 2024. All rights reserved.