Mybatis插入数据后返回插入对象的主键

       在mapper.xml中指定keyPropertyuseGeneratedKeys属性,其中id为返回的主键对应的java对象的属性       

useGeneratedKeys="true" keyProperty="id"

mapper.xml内容:

  
    insert into user(userName,password,comment)  
    values(#{userName}
  

javaBean内容:

public class User {  
    private int id;  //与keyProperty对应
    private String userName; 
    private String password;
    private String comment;       
    //setter and getter..... 
}

调用方式:

userDao.insert(user);//插入操作  
System.out.println("插入后主键为:"+user.getId());  //插入后会把主键id自动赋给user对象

 

你可能感兴趣的:(mybatis)