Spring JdbcTemplate Gets the primary key ID of the table that was increased by the Insert key

Source: Internet
Author: User

We are after the insert operation of the record of the table. Having such a requirement would require the primary key ID of that record to be insert. And the primary key ID of the table is the primary key self increment.
It is not possible to use the Max function of MySQL. Because at this point in the case of multiple users. The data is also inserted by other users in the datasheet. So the data may not be accurate.

The last time the author in pure JDBC case can get the ID of the primary key itself. Spring's jdbctemplate is just a encapsulation of JDBC. It can be done, too. And the code simplification is even more powerful.
The following shows a fragment of the code.


        Keyholder keyholder = new generatedKeyHolder ();
        PreparedStatementCreator PreparedStatementCreator = con-> {
            preparedstatement PS = con.preparestatement (" INSERT into  order_worker_quote_detail (work_quote_id, item_id, quantity, remarks) VALUES (' 1 ', ' 2 ', ' 120 ', ' Test expense name ') " , Statement.return_generated_keys);
            return PS;
        };

        Jdbctemplate.update (PreparedStatementCreator, keyholder);

        SYSTEM.OUT.PRINTLN ("See if you can get the final ID-------------->" + Keyholder.getkey (). Longvalue ());

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.