创建时间: | 2018/7/27 15:13 |
来源: | https://www.cnblogs.com/waterystone/p/5654300.html |
如下情况适用支持自增的DB,如MySQL。其他情况参见:MyBatis魔法堂:Insert操作详解(返回主键、批量插入)
1 2 3 4 5 6 | public class UserInfo { private int id; //主键自增ID private String userName; //姓名 private String account; //登陆账号 private String password; //密码 } |
1 2 3 | public interface UserInfoMapper { int addUser(UserInfo userInfo); } |
1 2 3 4 5 6 | <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" 是起作用的关键语句。
完整错误如下:
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里写成
1 2 3 4 5 6 | <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