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