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:
<id= "Insertandgetid" usegeneratedkeys= "true" Keyproperty= "UserId" parametertype= "Com.chenzhou.mybatis.User"> INSERT INTO User (username,password,comment) values (#{username},#{password},#{comment}) </ Insert >
Usegeneratedkeys:
Value Range True|false
The default value is: false.
Meaning: Sets whether to use the Getgenereatedkeys method of JDBC to get the primary key and assign the value to the domain model properties of the Keyproperty setting. MySQL and SQL Server execute auto-generated key field, so when the database is set to self-grow primary key, it can be obtained by the JDBC Getgeneratedkeys method. However, a database such as oralce that does not support auto-generated key field cannot get the primary key in this way.
Keyproperty:
(only useful for insert) marks an attribute, and MyBatis sets its value through Getgeneratedkeys or through the Selectkey child element of the INSERT statement. Default: Not set.
, we specify the keyproperty= "userid" in Insert, where the UserID represents the primary key attribute of the inserted user object.
Public class User { privateint userId; Private String userName; Private String password; Private String comment; // setter and Getter}
Public Interface Userdao { publicint insertandgetid (user user);}
Test:
New User (); User.setusername ("Chenzhou"); User.setpassword ("xxxx"); User.setcomment (" Test insert data Return PRIMARY key function "); System.out.println ("pre-insert primary key is:" +User.getuserid ()); Userdao.insertandgetid (user); // Insert Operation System.out.println ("Insert the key is:" +user.getuserid ());
Output:
Before inserting the primary key is: 0 Insert the main key is:15
Querying the database:
As shown above, the record that you just inserted has a primary key ID of 15
Mybatis+mysql returns the inserted primary key ID