mybatis与mysql插入数据返回主键

注意:使用的时候直接用user.getId
如:int count = reportDAO.insert(user);此时count为插入条数,user.getId()为主键
 
Xml代码  收藏代码
  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>  

 如上所示,我们在insert中指定了keyProperty="userId",其中userId代表插入的User对象的主键属性。

 

User.java

Java代码 
  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. }  
原文地址:https://www.cnblogs.com/xuzhenmin/p/3477108.html