Use generatedKeyHolder to get new data primary key value
Spring leverages generatedKeyHolder to provide a way to return new records to their primary key values:
int update (PreparedStatementCreator psc, Keyholder generatedKeyHolder)//The method returns the number of rows affected, Assign a new record corresponding primary key value to the generatedKeyHolder parameter
Spring for the Keyholder interface refers to a generic implementation class generatedKeyHolder, which returns the self-growing primary key value when a new record is added. Suppose we want to load a primary key value into an object after adding a forum plate object, you can adjust it by the following code:
FinalString insert_sql = "INSERT into gtable (Username,password) VALUES (?,?)"; Keyholder Keyholder=NewgeneratedKeyHolder (); intLines=jdbctemplate.update (NewPreparedStatementCreator () {//Create a PreparedStatement instance Publicpreparedstatement createpreparedstatement (Connection Connection)throwsSQLException {preparedstatement ps=connection.preparestatement (Insert_sql,NewString[] {"id"});//Create a PreparedStatement that binds self-increment through connectionPs.setstring (1, username);//when binding parameters, the sequence number starts at 1 instead of 0.Ps.setstring (2, password); returnPS; }}, Keyholder); Number Current_key=Keyholder.getkey (); System.out.println ("Modify line number:" +lines); System.out.println ("Current primary key:" +current_key);