• 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

  • 相关阅读:
    利用python脚本统计和删除redis key
    利用expect交互完成多台linux主机ssh key推送
    iptables -L很慢的原因
    tomcat各个端口的作用
    rabbitmq集群搭建
    ping 没有回icmp reply
    go mod 无法下载依赖问题
    0/1 nodes are available: 1 node(s) had taint
    go 编译:build constraints exclude all Go files in
    k8s单机部署
  • 原文地址:https://www.cnblogs.com/waterystone/p/5654300.html
Copyright © 2020-2023  润新知