Kazed

Pragmatic software development

  • Increase font size
  • Default font size
  • Decrease font size
Home Persistence

Getting the generated ID with Spring JdbcTemplate (in DB2)

Tags: java | persistence | spring


Automatically generated ID's are very handy, since you don't have to create the ID yourself and don't need a second roundtrip to the database as you would when you use a sequence

Example

Example table with books:
CREATE TABLE AUTHOR (
ID BIGINT NOT NULL GENERATED ALWAYS AS IDENTITY,
NAME VARCHAR(100) NOT NULL,
PRIMARY KEY(ID));

CREATE TABLE BOOK (
ID BIGINT NOT NULL GENERATED ALWAYS AS IDENTITY,
TITLE VARCHAR(100) NOT NULL,
AUTHOR_ID BIGINT NOT NULL,
PRIMARY KEY(ID));

When you insert a new book into the database, it will generate the ID automatically. However, when you need to insert multiple records with foreign key relations, like a author and a book record, where the author_id is the generated id of the author record, you need to determine the generated id.



Add this page to your favorite Social Bookmarking websites
Reddit! Del.icio.us! Mixx! Free and Open Source Software News Google! Live! Facebook! StumbleUpon! Yahoo! Free Joomla PHP extensions, software, information and tutorials.
Read more...