I am inserting many records using JDBC batch inserts.
Is there any way to get the generated key for each record?
Can I use ps.getGeneratedKeys()
with batch inserts?
I am using oracle.jdbc.OracleDriver
final String insert = "Insert into Student(RollNumber, Name, Age) values(StudentSEQ.nextval, ? , ?)";
final int BATCH_SIZE = 998;
int count = 0;
Connection con = null;
PreparedStatement ps = null;
try {
con = getConnection();
ps = con.prepareStatement(insert);
for (Student s : students) {
ps.setString(1, s.getName());
ps.setInt(2, s.getAge());
ps.addBatch();
count++;
if (count % BATCH_SIZE == 0) {
// Insert records in batches
ps.executeBatch();
}
}
// Insert remaining records
ps.executeBatch();
} finally {
if(ps != null)
ps.close();
release(con);
}
I am thinking of using ps.executeUpdate()
along with ps.getGeneratedKeys()
inside the loop to get the desired result. Any other solutions?
The JDBC 4.1 specification, section 13.6 Retrieving Auto Generated Values says:
It is implementation-defined as to whether
getGeneratedKeys
will return generated values after invoking theexecuteBatch
method.
So you will need to check if your driver actually supports it for batch updates. As indicated in the answer by Philip O., retrieval of generated keys is not supported with batch updates as documented in Oracle 12 JDBC Standards Support:
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.RETURN_GENERATED_KEYS);
Note: you may need to use one of the other generated keys prepare methods (prepareStatement(sql, columnIndexes)
or prepareStatement(sql, columnNames)
) as Oracle will return the ROW_ID
with the method in my example.
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