行の挿入から自動生成された 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
、行を挿入するときに呼び出されるべきだと思っていましたが
編集 :
行が挿入されると、自動インクリメント値が適切に作成されます
何か案が ?