MyBatis+MySQL returns the method of inserted primary key ID

  • 2020-07-21 07:34:01
  • OfStack

Requirement: After you insert a record into the MySQL database using MyBatis, you need to return the autoincrement primary key value for that record.

Method: Specify the keyProperty attribute in mapper, 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 specify keyProperty= "userId" in insert, where 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);  
} 

Testing:


User user = new User(); 
user.setUserName("chenzhou"); 
user.setPassword("xxxx"); 
user.setComment(" Test the insert data return primary key function "); 

System.out.println(" The primary key before insertion is: "+user.getUserId()); 
userDao.insertAndGetId(user);// The insert  
System.out.println(" After insertion, the primary key is: "+user.getUserId()); 

Output:

The primary key before insertion is: 0
After insertion, the primary key is: 15


Related articles: