您的位置:首页 > 其它

mybatis insert 插入数据成功后返回值为 null

2018-03-18 19:30 274 查看
第一种方法: 
<!-- ***************重点掌握插入语句返回结果的做法**************** -->
  <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());
版权声明:本文为博主原创文章,未经博主允许不得转载。 http://blog.csdn.net/qq_25816185/article/details/58071982
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: