- Spring Jdbc Auto-generate Primary Key Example
- Spring Jdbc Auto-generated Primary Key Mean
- Spring Jdbc Auto-generated Primary Key Data
- Related Questions & Answers
A quick and practical guide to getting autogenerated keys when working with Spring JDBC. Obtaining Auto-generated Keys in Spring JDBC. Of primary keys. 6.4 Retrieving AUTOINCREMENT Column Values through JDBC Before version 3.0 of the JDBC API, there was no standard way of retrieving key values from databases. Spring JDBC FAQ: How do I retrieve the auto-generated database key for a serial field (also known as an autoincrement field in MySQL) after I perform a SQL INSERT using Spring JDBC? (I'm not phrasing that well, but by this question I mean the value of the primary key for the record I just inserted. Now, let's implement a method which will use JDBCTemplate to insert the new record and return the auto-generated id. Therefore, we'll use the JDBCTemplate update method which supports the retrieval of primary keys generated by the database. This method takes an instance of the PrepareStatementCreator interface as the first argument and the other argument is the KeyHolder.
- Selected Reading
JDBCObject Oriented ProgrammingProgramming
If you insert records into a table which contains auto-incremented column, using a Statement or, PreparedStatement objects.
You can retrieve the values of that particular column, generated by them object using the getGeneratedKeys() method.
Example
Let us create a table with name sales in MySQL database, with one of the columns as auto-incremented, using CREATE statement as shown below −
Spring Jdbc Auto-generate Primary Key Example
Retrieving auto-generated values (PreparedStatement object)
Following JDBC program inserts 3 records into the Sales table (created above) using PreparedStatement, retrieves and displays the auto-incremented values generated by it.
Example
Spring Jdbc Auto-generated Primary Key Mean
Output
Retrieving auto-generated values (Statement object)
Following JDBC program inserts 3 records into the Sales table (created above) using Statement, retrieves and displays the auto-incremented values generated by it.