Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there anyway to get the generated keys when using Spring JDBC batchUpdate?

Tags:

java

spring

jdbc

I am using JDBC and want to batch insert, but I need the generated keys for the next round of inserts - is there anyway to accomplish this?

MapSqlParameterSource[] batchArgs ....

DAL.getNamedParameterTemplate().batchUpdate("INSERT INTO...", batchArgs);

Thanks

like image 674
MalcomTucker Avatar asked Mar 11 '10 09:03

MalcomTucker


People also ask

Which interface is provided by Java Spring to generate primary key?

KeyHolder Interface is for retrieving keys, typically used for auto-generated keys as potentially returned by JDBC insert statements. Implementations of this interface can hold any number of keys. In the general case, the keys are returned as a List containing one Map for each row of keys.

What is the return value of JdbcTemplate update?

it will return 1 for success and 0 for failure case so, according to it you can process your logic.

What is Spring JDBC How is different from JDBC?

The Spring JDBC Template has the following advantages compared with standard JDBC. The Spring JDBC template allows to clean-up the resources automatically, e.g. release the database connections. The Spring JDBC template converts the standard JDBC SQLExceptions into RuntimeExceptions.

What is SimpleJdbcInsert?

A SimpleJdbcInsert is a multithreaded, reusable object providing easy insert capabilities for a table. It provides meta-data processing to simplify the code needed to construct a basic insert statement. All you need to provide is the name of the table and a Map containing the column names and the column values.


1 Answers

Spring framework folks attempted a solution to this problem. But they abandoned the attempt when it became apparent that there is no way to guarantee that the solution will work with all JDBC Drivers. This is because the JDBC spec doesn't guarantee that the generated keys will be made available after a batch update. JDBC drivers are free to implement this feature as they see fit. In some cases the underlying database might not return the generated keys making it impossible for the driver to support this feature.

So even if you are directly working with JDBC, you will need to check whether your database and JDBC driver makes the generated keys available.

I remember I was able to achieve this with MySQL 5.0 JDBC driver with some effort but never integrated the solution in our production application as we had to support older versions of MySQL as well.

like image 172
Tahir Akhtar Avatar answered Oct 14 '22 12:10

Tahir Akhtar