Source address: http://chenzhou123520.iteye.com/blog/1849881
== The following content is reproduced by me from someone else's BLOG for my own collection =============================== =
Requirement: After inserting a record into the MySQL database using MyBatis, the self-incrementing primary key value of the record needs to be returned.
Method: Specify the keyProperty property in the mapper, the example is as follows:
- <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 keyProperty="userId" in insert, where userId represents the primary key property 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: " +user.getUserId());
- userDao.insertAndGetId(user); //Insert operation
- System.out.println( "Primary key after insertion: " +user.getUserId());
output:
- The primary key before insertion is: 0
- After inserting the primary key is: 15
Query the database:
As shown above, the primary key id of the record just inserted is 15