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:
<insert id= "Insertandgetid" usegeneratedkeys= "true" keyproperty= "UserId" parametertype= " Com.chenzhou.mybatis.User ">insert into User (username,password,comment) VALUES (#{username},#{password},#{ Comment}) </insert>
As shown above, we specified the keyproperty= "userid" in Insert, where the UserID represents the primary key attribute of the inserted user object.
User.java
public class User {private int userid;private string Username;private string Password;private string Comment;//setter and Getter
Userdao.java
Public interface Userdao {public int insertandgetid (user user);}
Test:
User user = new user (), User.setusername ("Chenzhou"), User.setpassword ("xxxx"), user.setcomment ("Test insert data Return primary key function"); SYSTEM.OUT.PRINTLN ("PRIMARY key before insertion is:" +user.getuserid ()); Userdao.insertandgetid (user);//insert Operation SYSTEM.OUT.PRINTLN ("Insert main key to:" +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