Mybaits-@Options(useGeneratedKeys = true, keyProperty = "xxxx")作用

Mybaits之@Options(useGeneratedKeys = true, keyProperty = “xxxx”)作用

useGeneratedKeys 设置为"true"表明要 MyBatis 获取由数据库自动生成的主键;

keyProperty="id"指定把获取到的主键值注入到 XXX(实体类) 的 id 属性。

如配置中开启了@Options(useGeneratedKeys = true")

再这样插入数据则会报

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.executor.ExecutorException: No setter found for the keyProperty ‘id’ in com.xx.xx.entity.xxxx.

    @Insert({
        "insert into tb_major (major_id, major_desc, ",
        "major_certificates_id)",
        "values (#{majorId,jdbcType=BIGINT}, #{majorDesc,jdbcType=VARCHAR}, ",
        "#{majorCertificatesId,jdbcType=BIGINT})"
    })
    int insert(Major record);

所以得改为

    @Insert({
        "insert into tb_major (major_id, major_desc, ",
        "major_certificates_id)",
        "values (#{majorId,jdbcType=BIGINT}, #{majorDesc,jdbcType=VARCHAR}, ",
        "#{majorCertificatesId,jdbcType=BIGINT})"
    })
    @Options(useGeneratedKeys = true, keyProperty = "majorId")
    int insert(Major record);
数据库 MySQL

你可能感兴趣的:(Mybaits)