在插入数据后,有时候会想返回插入的数据,但是id好像是不能的,现在来介绍mybatis插入后返回id的方法。

MySQL下,id为自增类型时,插入前加入 SELECT LAST_INSERT_ID()

<insert id="addTopLine" parameterType="com.kigang.entity.TopLine">
        <selectKey keyProperty="topId" order="AFTER" resultType="java.lang.Integer">
            SELECT LAST_INSERT_ID()
        </selectKey>
        INSERT into `top_line` (user_id,top_title,top_content,top_image_url,audit_status) VALUES(#{userId},#{topTitle},#{topContent},#{topImageUrl},#{auditStatus})
    </insert>

在执行插入方法前后输出数据,可以看到id变获取了。

当id是UUID类型时,调用 select UUID()

<insert id="addTopLine" parameterType="com.kigang.entity.TopLine">
        <selectKey keyProperty="id" order="AFTER" resultType="java.lang.String">
            SELECT UUID()
        </selectKey>
        INSERT into `top_line` (user_id,top_title,top_content,top_image_url,audit_status) VALUES(#{userId},#{topTitle},#{topContent},#{topImageUrl},#{auditStatus})
    </insert>

差不多就是这样,以前还想着插入后要怎么获取id,现在这个触发器的方式,真的很好用。
更多请参考:MyBatis框架——mybatis插入数据返回主键(mysql、oracle)

更多推荐

mybatis实现插入后返回id