0

I am using Spring-Jdbc template(first timer) to create MySql repository. I have tables that use AutoIncrement columns as primary key.

I wonder if there a way to get newly generated Ids (autoInc) with each successful batch create statement?

Any pointers or sample would be a great help.

Thanks Panks

Panks
  • 601
  • 1
  • 11
  • 20
  • possible duplicate of [How to get the insert ID in JDBC?](http://stackoverflow.com/questions/1915166/how-to-get-the-insert-id-in-jdbc) – eggyal Jun 06 '12 at 17:57

1 Answers1

0

Use getGeneratedKeys() method from your Statement or PreparedStatement object to identify the new auto generated values. Iterate the returned ResultSet object to get the newly generated key values in the order of batch statements.

This call may throw java.sql.SQLFeatureNotSupportedException if the JDBC driver, that you are using, does not support this method.

Sample code snippet:

String sql_insert =  
    "insert into my_table ( non_auto_incrmnt_fld_names_,_separated ) " +  
                 " values ( record1 ), ( record2 )"; // append as many as required  
...  
int rowsAffected = stmtObject.executeUpdate( sql_insert, Statement.RETURN_GENERATED_KEYS );  
ResultSet rs = stmtObject.getGeneratedKeys();  

//******************************************************  
rs.last();  
int rows = rs.getRow();  
System.out.println( "Generated keys count: " + rows );  
int currentRow = 1;  
rs.beforeFirst();  
//******************************************************/  

while( rs.next() ) {  
    System.out.println( /**/( currentRow++ ) + " = " + /**/rs.getInt( 1 ) );  
} // while rs  
Ravinder Reddy
  • 23,692
  • 6
  • 52
  • 82
  • Thanks Ravinder, That solution goes with raw jdbc. I am working with spring jdbctemplates. I found one solution for it using spring jdbc- [link] http://stackoverflow.com/questions/1665846/identity-from-sql-insert-via-jdbctemplate But I am looking for a solution for batch update. – Panks Jun 07 '12 at 04:15