1.如果是使用generator来自动化的这种,在配置中请加入红色配置,这样能够返回id
<table schema="" tableName="user" domainObjectName="User"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false">
<property name="useActualColumnNames" value="true"/>
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
解释 generatedKey 是生成主键的意思
column 是列名,与数据库中的名称一致
sqlStatement 是指SQL语句
identity 如果为true,则该列标记为标识列,生成的<selectKey>元素将放置在插入之后(对于标识列)。如果为false,则生成的<selectKey>将放置在插入之前(通常用于序列)。
关于identity的详细解释见下图。截取自mybatis-generator官方文档
2.在已生成的xml中添加
(1)
<insert id="insert" parameterType="User" keyProperty="id"
keyColumn="ID" useGeneratedKeys="true">
将直接把主键注入到pojo中,例如:
customerMapper.insert(customer);
如上配置xml后,在执行上述代码前customer getId的结果为null。
执行过后customer getId会返回刚刚插入的数据的id。
(2)
<insert id="insertSelective" parameterType="xxxx" >
<selectKey resultType="java.lang.Integer" keyProperty="ID" order="AFTER" >
SELECT LAST_INSERT_ID()
</selectKey>
insert into XXXX
这里的keyProperty是对应的是<ResultMap>中的property,并不是表中的字段名。
order="AFTER"是指在插入数据之后查询主键,也需要通过getId方法来获取。
order="BEFORE"是指在获取主键后再插入数据,也需要通过getId方法来获取。
(3)
如果没有<ResultMap>使用如下方法
<selectKey resultType="Integer" order="AFTER" keyProperty="user.userId">
SELECT LAST_INSERT_ID() AS userId
</selectKey>
获取的方法与上面的相同。