1、坑

使用mybatis时执行insert方法时

<insert id="insert" useGeneratedKeys="true" keyProperty="id"        parameterType="com.sanshi.searchforblog.entity.Article" >  
insert into t_article (title, author, content)  
values (#{title,jdbcType=VARCHAR}, #{author,jdbcType=VARCHAR}, #{content,jdbcType=LONGVARCHAR})
</insert>

会返回自增主键,但是多次调用

int id = articleMapper.insert(article);

后得到的id都是1,换用其他方式的配置

<selectKey resultType="Integer" keyProperty="id" order="AFTER">
SELECT LAST_INSERT_ID()
</selectKey>

仍旧得到的是1。百思不得其解。

2、解

网上多番搜索,终于知道原因,是因为insert返回的值是受影响的行数,插入后的id放入了实体对象中

图片说明

由此可以直接获取自增id