MyBatis insert后返回自增字段的值

时间:2023-03-09 15:43:52
MyBatis insert后返回自增字段的值

如下情况适用支持自增的DB,如MySQL。其他情况参见:MyBatis魔法堂:Insert操作详解(返回主键、批量插入)

1.model

public class UserInfo {
private int id;//主键自增ID
private String userName;//姓名
private String account;//登陆账号
private String password;//密码
}

  

2.UserInfoMapper.java

public interface UserInfoMapper {
int addUser(UserInfo userInfo);
}

  

3.UserInfoMapper.xml

<insert id="addUser" parameterType="com.xxx.model.UserInfo" useGeneratedKeys="true" keyProperty="id">
INSERT INTO
user_info(user_name, account, password)
values
(#{userName},#{account},#{password})
</insert>

  

这样,在插入后,MySQL自增的id就会设置到原来的userInfo对象里。

其中 useGeneratedKeys="true" keyProperty="id" 是起作用的关键语句。

4.QA

4.1 报错:org.apache.ibatis.binding.BindingException: Parameter 'id' not found

完整错误如下:

org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.executor.ExecutorException: Error getting generated key or setting result to parameter object. Cause: org.apache.ibatis.binding.BindingException: Parameter 'id' not found. Available parameters are [userInfo, param1]

这是因为在addUser()的对象参数前加@Param("userInfo"),而在mapper.xml里写成

<insert id="addUser" parameterType="com.xxx.model.UserInfo" useGeneratedKeys="true" keyProperty="id">
INSERT INTO
user_info(user_name,, account, password)
values
(#{userinfo.userName},#{userInfo.account},#{userInfo.password})
</insert>

这种情况在不返回自增值是没有问题的,但一旦设置了useGeneratedKeys就报错。所以养成良好的习惯,没事少加@Param!!!

end