JDBC: Get Last Insert's ID
OK, so I need this frequently enough to care (when I do direct JDBC for some data-mining, data-migration or any other mass-db operations) but not frequently enough to memorize (as I use Hibernate normally). Therefore, it seems like a good idea to post it here and be able to find it later, if I need it again :)
Oh, and maybe somebody else may benefit from it too. Heh
So, if, in JDBC, you need to get the IDs of the last inserts when using auto_generated primary keys on the database side (e.g. sequences) you should use getGeneratedKeys() method of java.sql.PreparedStatement
resultSet = pstmt.getGeneratedKeys();
if ( resultSet != null && resultSet.next() )
{
newid = resultSet.getInt(1);
}
The example shows how to get one ID but you can get all IDs of a mass-insert, as well. Pretty cool.