mybatis获取新增记录的id是比较常见的操作. 简单配置即可达到目的,如下:
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long">
SELECT LAST_INSERT_ID()
</selectKey>
今天使用的过程中发现以上的配置不能获取到新增id, 对比了下之前的代码, 主要是在mapper接口中对参数添加了@Param("record")注解, mapper接口如下:
int insert(@Param("record") Wechat record, @Param("modelName") String modelName);
解决方法, 就是在mapper.xml的keyProperty处也添加上变量的别名, 如下:
<selectKey keyProperty="record.id" order="AFTER" resultType="java.lang.Long">
SELECT LAST_INSERT_ID()
</selectKey>