The problem
I have a table for some data that has an ID
column of type integer (which is also the primary key).
When a new data entry is added to the table, it should get a new ID whereas the ID is not known by the application that inserts the object but it should be given by the database. For example, the IDs should be assigned like 0, 1, 2, ...
Assume that I have all other data for the new entry, how would I do the insert? Normally:
insert into T values(123, 'data');
But now I don't know what to put instead of 123
- would you create some kind of global variable NEXTID
in the database that provides the IDs and query/update this value each time before inserting into T
?
The questions
- How to handle this kind of problem? A solution that is concurrency save is preferable.
- How to achieve this with Java/myBatis? I Have a Java class that corresponds to the table structure and a new object should be added to the database, getting a new ID automatically.
Update
What I searched for was auto-increment.
- Is there a standard SQL way (database independent) of declaring a column as auto-increment? I am using Apache Derby and
GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1)
is suggested here. - How does the insert to a table that contains auto-increment columns look like?
- What is the best way to get the created auto-increment value after an insert when simultaneaous access to the database is possible?
I'll accept an answer that includes explanation and SQL instructions for declaration and insertion :)