title: Getting auto-generated key from row insertion in spring 3 / PostgreSQL 8.4.9
body: <p>I would like to retrieve the auto-generated id from a row insertion, but I get a <code>NullPointerException</code></p>
  
  <p>Here is the code :</p>
  
  <pre><code>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 &gt; 0)
              result = keyHolder.getKey().longValue(); //line 72
  </code></pre>
  
  <p>And this is the PostgreSQL table :</p>
  
  <pre><code>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 )
  );
  </code></pre>
  
  <p>PostgreSQL supports auto-generated keys, but I get this exception :</p>
  
  <pre><code>java.lang.NullPointerException
      at com.tante.db.JDBCUserAccountDAO.insertAccount(JDBCUserAccountDAO.java:72)
  </code></pre>
  
  <p>EDIT :
  I tried this to get the auto generated key :</p>
  
  <pre><code>result = jdbcTemplate.queryForLong("select currval('compte_idcompte_seq')");
  </code></pre>
  
  <p>but I get a <code>PSQLException</code> : </p>
  
  <p><code>the current value (currval) of the sequence compte_idcompte_seq is not defined in this session</code>, although I thought that <code>compte_idcompte_seq.NEXTVAL</code>
  should have been called when inserting the row</p>
  
  <p>EDIT : </p>
  
  <p>The auto-increment value is properly created when a row is inserted</p>
  
  <p>Any idea ?</p>