MyBatis+MySQL returns the inserted primary key ID

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:

Xml code   Favorite code
  1. <insert id="insertAndGetId" useGeneratedKeys="true" keyProperty="userId" parameterType="com.chenzhou.mybatis.User">  
  2.     insert into user(userName,password,comment)  
  3.     values(#{userName},#{password},#{comment})  
  4. </insert>  

 As shown above, we specified keyProperty="userId" in insert, where userId represents the primary key property of the inserted User object.

 

User.java

Java code   Favorite code
  1. public class User {  
  2.     private int userId;  
  3.     private String userName;  
  4.     private String password;  
  5.     private String comment;  
  6.       
  7.     //setter and getter  
  8. }  

 UserDao.java

Java code   Favorite code
  1. public interface UserDao {  
  2.   
  3.     public int insertAndGetId(User user);  
  4.   
  5. }  

 test:

Java code   Favorite code
  1. User user = new User();  
  2. user.setUserName("chenzhou");  
  3. user.setPassword("xxxx");  
  4. user.setComment( "Test insert data return primary key function" );  
  5.   
  6. System.out.println( "Primary key before insertion: " +user.getUserId());  
  7. userDao.insertAndGetId(user); //Insert operation  
  8. System.out.println( "Primary key after insertion: " +user.getUserId());  

 output:

Shell code   Favorite code
  1. The primary key before insertion is: 0  
  2. After inserting the primary key is: 15  

 Query the database:

 

As shown above, the primary key id of the record just inserted is 15

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326356436&siteId=291194637