mybatis插入语句执行后返回结果

第一种方法: 

<!-- ***************重点掌握插入语句返回结果的做法**************** -->

  <insert id="insertUser" parameterType="cn.com.gjw.pojo.User">
  <!-- 将插入数据的主键返回,由SELECT LAST_INSERT_ID()得到,只适用于自增主键 
  keyProperty:指定将查询到的结果返回到parameterType所指的对象的对应属性中
  order:指的是执行顺序,即为AFTER时,则在insert语句执行之后执行。
  -->
  <selectKey keyProperty="id" order="AFTER" resultType="int">
  SELECT LAST_INSERT_ID()
  </selectKey>
  insert into user(userName, sex, address, birthday) values(#{userName}, #{sex}, #{address}, #{birthday})

  </insert>


第二种方法:

<insert id="insertUser" parameterType="cn.com.gjw.pojo.User" useGeneratedKeys="true" keyProperty="id">
  insert into user(userName, sex, address, birthday) values(#{userName}, #{sex}, #{address}, #{birthday})
</insert>


第三种方法:如果id不是自增的,当表中没有记录式,设置id值为1,否则取id的最大值加2作为新的主键,设置方式为:

<insert id="insertUser" parameterType="cn.com.gjw.pojo.User" useGeneratedKeys="true" keyProperty="id">
  <selectKey keyProperty="id" order="BEFORE" resultType="int">
  select if(max(id) is null, 1, max(id) + 2) as newId from user
  </selectKey>
  insert into user(userName, sex, address, birthday) values(#{userName}, #{sex}, #{address}, #{birthday})
</insert>


代码中,执行完插入操作后可以打印测试是否取到了刚插入的记录的id:

System.out.println(user.getId());

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值