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
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.
it will return 1 for success and 0 for failure case so, according to it you can process your logic.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With