Mybatis_插入数据后返回主键ID_数据库字段名与类中属性名不一致的处理办法

一般来说,在使用mybatis插入数据后,由于使用了自增主键,自增完后的主键ID会被自动设置为对应对象的属性值,一般为id

可是今天,我遇到了问题,再插入一条数据后,发现这个自增ID无法被设置为对象的属性值.

后来排查问题,发现数据库中的主键的字段名和类中的属性名不一致.

我迅速找到了解决办法:

在mybatis中的insert标签中使用selectKey标签:

1     <insert id="addUser" useGeneratedKeys="true" keyProperty="user_id" parameterType="user">
2         <selectKey keyProperty="userId" order="AFTER" resultType="java.lang.Integer">
3             SELECT LAST_INSERT_ID()
4         </selectKey>
5         insert into sp_user(`username`, `password`, `user_email`, `user_tel`, `create_time`, `update_time`)
6          values (#{username}, #{password}, #{userEmail}, #{userTel}, #{createTime}, #{updateTime})
7 
8     </insert>