第一种方法:
<!-- ***************重点掌握插入语句返回结果的做法**************** -->
<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());