MyBatis返回插入的主键ID

使用MyBatis,通常我们都会执行这一步新增的操作:

int count = this.projectMapper.addProject(projectBuildingInfoVO);

count 表示影响的行数。
在将VO对象传到mapper层的时候,projectBuildingInfoVO 并没有id,id设置的是自增。

需求:使用MyBatis往MySQL数据库中插入一条记录后,需要返回该条记录的自增主键值。

一、xml方式

<insert id="addProject" parameterType="com.coolead.module.model.vo.ProjectBuildingInfoVO">

    <selectKey resultType="java.lang.Integer" keyProperty="id" order="AFTER">
        SELECT LAST_INSERT_ID()
    </selectKey>
    
    insert into tb_project
    <trim prefix="(" suffix=")" suffixOverrides=",">
        <if test="id != null">id,</if>
        <if test="fullName != null">full_name,</if>
        ......
        ......
</insert>

关键代码就是<selectKey>这段,keyProperty表示的是VO对象中id属性的属性名,SELECT LAST_INSERT_ID()表示的就是最后插入的这条数据的主键id.

这样新增之后,projectBuildingInfoVO对象就有id了。

二、注解方式

@Insert("insert into tb_user(xx,xx) values(#{xx},#{xx})") 
@SelectKey(statement = "SELECT LAST_INSERT_ID()", keyProperty = "id", before = false, resultType = int.class) 
Integer save(User user);
原文地址:https://www.cnblogs.com/VitoYi/p/7852758.html