Mybatis+mysql returns the inserted primary key ID

Source: Internet
Author: User

Requirement: After you insert a record into the MySQL database using MyBatis, you need to return the self-increment primary key value for that record.

Method: Specify the Keyproperty property in Mapper, as shown in the following example:

 1  <  insert  id  = "Insert"   Usegeneratedkeys  = "true"   Keyproperty  = "id"   ParameterType  = "Com.koala.blog.model.Test"  >  2   INSERT INTO Test (ID, name)  3   4  </ insert  >  

As shown above, we specified keyproperty= "id"in Insert, where the ID represents the primary key attribute of the inserted test object.

Also be clear usegeneratedkeys= "true" otherwise it will not work

Model,dao is automatically generated by MyBatis generator

Methods for using unit test tests:

1 @Test2  Public voidTestinsert () {3Com.koala.blog.model.Test Test =Newcom.koala.blog.model.Test ();4Test.setname ("haha");5     intresult =Testservice.insert (test); // result refers to inserting a few records6 Logger.info (Test.getid ()); // Test.getid () is the primary key to get new records7}

This method applies to the self-increment primary key of the primary key int

Non-self-increment primary key requires setting primary key to insert data correctly, so it is not configured with Usegeneratedkeys= "true" keyproperty= "id"

can be correctly obtained Test.getid ()

Mybatis+mysql returns the inserted primary key ID

Related Article

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.