JDBC precompiled processing and spring return self-increment primary key values

Source: Internet
Author: User

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);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.