MySQL insert返回主键

1、通过mybatis generator自动生成的

在generator配置文件中(generatorConfig.xml)插入<generatedKey column="id" sqlStatement="MySql" identity="true"/>,使用生成的insert方法,主键值包装在了参数对象里边,通过user.getId()获取 
如:

<table tableName="t_approval_process" domainObjectName="ApprovalProcess" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
    <generatedKey column="id" sqlStatement="MySql" identity="true"/>
        </table>
  • 1
  • 2
  • 3

2、手动添加

1、insert按如下修改,主键值包装在了参数对象里边,通过

user.getId()获取

<insert id="insert" parameterType="user" keyProperty="id" useGeneratedKeys="true">
  • 1

2、插入selectKey标签,获取同上

<insert id="insert" parameterType="com.mmall.pojo.ApprovalProcess" >
    <selectKey resultType="java.lang.Long" keyProperty="id" order="AFTER" >
      SELECT LAST_INSERT_ID()
    </selectKey>
    insert into a (name, type)
    values(#{name}, #{type})
  </insert>
原文地址:https://www.cnblogs.com/hzcya1995/p/13300665.html