Thursday, April 10, 2008

Postgresql - Generate Primary Key before Insert

First define the primary key column as serial, it is a integer, but a sequence table will be created automatically to match it. For example, if you define an April_ID as type serial in table April, a sequence table called April_April_ID_SEQ will be created automatically when creating the April table.

Second in your program, use select nextval('schema.april_april_id_seq') to obtain the next value for primary key. You don't need to plus 1 since Postgresql does it for you. If using Spring JDBC template, just call getJdbcTemplate().queryForInt(the sql).

Third, use the value just obtained as parameter in the insert sql.

Done.

No comments: