![Keys Keys](/uploads/1/2/5/8/125871670/463680982.png)
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. Mar 01, 2012 Let’s see how we can perform batch insert in Java using JDBC APIs. Although you might already knew this, I will try to explain the basic to a bit complex scenarios. In this note, we will see how we can use JDBC APIs like Statement and PreparedStatement to insert data in any database in batches.
The Microsoft JDBC Driver for SQL Server supports the optional JDBC 3.0 APIs to retrieve automatically generated row identifiers. The main value of this feature is to provide a way to make IDENTITY values available to an application that is updating a database table without a requiring a query and a second round-trip to the server.
Jdbc Batch Size
Because SQL Server doesn't support pseudo columns for identifiers, updates that have to use the auto-generated key feature must operate against a table that contains an IDENTITY column. SQL Server allows only a single IDENTITY column per table. The result set that is returned by getGeneratedKeys method of the SQLServerStatement class will have only one column, with the returned column name of GENERATED_KEYS. If generated keys are requested on a table that has no IDENTITY column, the JDBC driver will return a null result set.
You cannot combine auto-generated keys with batch update. In any case if it is supported by your driver than your statement prepare should be changed to the code below to instruct the driver to retrieve generated keys: ps = con.prepareStatement(insert, Statement.RETURNGENERATEDKEYS). Here's a quick look at how to get the generated key from a MySQL database table after performing a SQL INSERT statement on a table that has an autoincrement field. (Some databases also refer to this as an identity field.).
![Spring Spring](/uploads/1/2/5/8/125871670/779585494.jpg)
As an example, create the following table in the sample database:
In the following example, an open connection to the sample database is passed in to the function, an SQL statement is constructed that will add data to the table, and then the statement is run and the IDENTITY column value is displayed.