MYBATIS-mybatis批量插入返回主键ID报错

问题

使用mybatis进行批量插入的时候,并且数据库设置的是主键递增,并且在插入的时候需要返回主键id的时候,报null错误。也就是查询不到刚刚插入到数据库的id。

背景:

springboot+mbatis+插件spring-boot-mybatis-rw
关于插件spring-boot-mybatis-rw 是做什么的,请见博客https://blog.csdn.net/lifen0908/article/details/102897422

解决方案

批量插入代码

int batchInsert(@Param("records") List<BatchConf> list);
 <insert id="batchInsert"  useGeneratedKeys="true" keyProperty="id"  parameterType="java.util.List">
        insert into batch_conf (
        url,
        title,
        keywords,
        create_time,
        update_time)
        values
        <foreach collection="records" item="record" separator=",">
            ( 
            #{record.url,jdbcType=VARCHAR},
            #{record.title,jdbcType=VARCHAR},
            #{record.keywords,jdbcType=VARCHAR},
            #{record.createTime,jdbcType=TIMESTAMP},
            #{record.updateTime,jdbcType=TIMESTAMP})
        </foreach>
    </insert>

在mybatis中,假如没有插件spring-boot-mybatis-rw ,那么按照上面的写法,在xml中加入了useGeneratedKeys=“true” keyProperty=“id” 是可以返回主键了。但是加入了插件,就变成了插入数据到主库,但是查询主键id是在从库,导致在从库中查询不出来id。

不能改变项目的结构,那么就改成思路。

  1. 批量返回不了主键id,那就单条的进行插入,然后汇总得到主键ids。

  2. 先不加useGeneratedKeys=“true” keyProperty=“id”。也就是直接批量插入数据库,然后根据是插入了数据库的n条,再从数据库中查询id为前n的id的记录。这样直接分开写了,由一个批量插入变成了批量插入+查询前n条刚刚插入的数据的ids。

你可能感兴趣的:(#,mysql,#,mybatis,Java)