在往数据库插入数据时有一些自增的字段,有时刚刚插入进去就要用这些自增字段的值,这时这个字段的值是null的,所以怎么能在插入的时候就立刻获得这个字段的值呢,下面总结了几种方法。
第一种 利用useGeneratedKeys=“true” keyProperty=“proId” 其中keyPropertry是对象中对应数据库中主键的属性。
<insert id="insertProject" useGeneratedKeys="true" keyProperty="proId" parameterType="cn.bookcycle.base.pojo.po.Project" >
insert into tb_project_sum(software_right, game_name,game_num,skill_share,user_id,date)
values(#{softwareRight},#{gameName},#{gameNum},#{skillShare},#{userId},#{date})
</insert>
第二种 这种情况可以通过在MyBatis中配置selectKey 为mysql的LAST_INSERT_ID()函数获得插入时的自增序列值来获得。
<insert id="insertReport" parameterType="cn.bookcycle.base.pojo.po.Progress">
<selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="progressid">
SELECT LAST_INSERT_ID()
</selectKey>
insert into tb_progress
(progress_id, segement_id, viewed,todo_id)
values (#{progressid}, #{segementid}, #{viewed},#{todoid})
</insert>
第三种
更为详细的原理介绍下面的这个博客解释的很好https://www.jianshu.com/p/181144b9333f