Requirement: after a record is inserted into the MySQL database using MyBatis, the auto-increment primary key value of the record needs to be returned.
Method: Specify the keyProperty in mapper, for example:
Xml Code 650) this. width = 650; "class =" star "src =" http://www.bkjia.com/uploads/allimg/131228/16042631Y-0.png "alt =" add to favorites code "style =" border: 0px; "/>
-
<Insertid = "insertAndGetId" useGeneratedKeys = "true" keyProperty = "userId" parameterType = "com. chenzhou. mybatis. User">
-
Insert into user (userName, password, comment)
-
Values (# {userName}, # {password}, # {comment })
-
</Insert>
As shown above, keyProperty = "userId" is specified in insert, where userId represents the primary key attribute of the inserted User object.
User. java
Java code 650) this. width = 650; "class =" star "src =" http://www.bkjia.com/uploads/allimg/131228/16042631Y-0.png "alt =" add to favorites code "style =" border: 0px; "/>
-
Publicclass User {
-
Privateint userId;
-
Private String userName;
-
Private String password;
-
Private String comment;
-
-
// Setter and getter
-
}
UserDao. java
Java code 650) this. width = 650; "class =" star "src =" http://www.bkjia.com/uploads/allimg/131228/16042631Y-0.png "alt =" add to favorites code "style =" border: 0px; "/>
-
Publicinterface UserDao {
-
-
Publicint insertAndGetId (User user User );
-
-
}
Test:
Java code 650) this. width = 650; "class =" star "src =" http://www.bkjia.com/uploads/allimg/131228/16042631Y-0.png "alt =" add to favorites code "style =" border: 0px; "/>
-
User user = new User ();
-
User. setUserName ("chenzhou ");
-
User. setPassword ("xxxx ");
-
User. setComment ("test the primary key function for data insertion ");
-
-
System. out. println ("primary key before insertion:" + user. getUserId ());
-
UserDao. insertAndGetId (user); // insert operation
-
System. out. println ("primary key after insertion:" + user. getUserId ());
Output:
Shell code 650) this. width = 650; "class =" star "src =" http://www.bkjia.com/uploads/allimg/131228/16042631Y-0.png "alt =" add to favorites code "style =" border: 0px; "/>
-
Primary Key before insertion: 0
-
Primary Key after insertion: 15
Query the database:
650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/16042A521-5.jpg "style =" border: 0px; "height =" 61 "width =" 616 "/>
As shown above, the primary key id of the newly inserted record is 15