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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM