Mybatis新增数据返回该条记录的主键

有时我们需要在插入一条数据以后,希望能返回它的一个主键信息,mybatis底层为我们提供了这种方法
1:通过selectKey标签对实现

<insert id="insertStudent">
   insert into student(name,email,age)
   values(#{name},#{email},#{age})
   <selectKey keyProperty="id" resultType="java.lang.Integer">
            select LAST_INSERT_ID() as id
   </selectKey>
</insert>

此种方法需注意,传入的参数不可用@Param修饰

2:通过insert 标签对实现

<insert id="insertStudent" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
   insert into student(name,email,age)
   values(#{name},#{email},#{age})
</insert>

此种方式更为简洁

发布了27 篇原创文章 · 获赞 1 · 访问量 842

猜你喜欢

转载自blog.csdn.net/weixin_44971379/article/details/105083397