mybits自增返回主键问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/king866/article/details/70170754

获取自增ID解决办法:

方法:在mapper中指定keyProperty属性,示例如下: 

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

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

User user = new User();

user.setUserName("chenzhou");

user.setPassword("xxxx");

user.setComment("测试插入数据返回主键功能");

int userId= userDao.insertAndGetId(user);//插入操作

当我们获取userId时,该id可能是数据库返回的受影响行数 ,也就是1

但是mybits自动 帮我们把userId,设置到了user中

因此应该:

userDao.insertAndGetId(user);//插入操作

扫描二维码关注公众号,回复: 3139884 查看本文章

String userId=user.getUserId();


猜你喜欢

转载自blog.csdn.net/king866/article/details/70170754
今日推荐