Mybatis批量插入数据(Oracle与MySQL)

主要不同在于foreach标签内separator属性的设置问题:

  • separator设置为","分割时,最终拼接的代码形式为:insert into table_name (a1,b2,c3) values (v1,v2,v3) ,(v4,v5,v6) ,...
  • separator设置为"union all"分割时,最终拼接的代码形式为:insert into table_name (a1,b2,c3) values (v1,v2,v3) union all (v4,v5,v6) union all...

详情请见示例代码:

Oracle

<!--注意:有长度限制,不需要像mysql添加VALUES -->
<insert id="inser" parameterType="com.my.code.User">
	insert into table_name (name, pwd, age)
	<foreach collection="list" item="item" index="index" separator="union all">
		(select #{item.name}, #{item.pwd}, #{item.age} from dual )
	<foreach>
</insert>

MySQL

<insert id="inserData" parameterType="com.my.code.User">
	insert into table_name (name, pwd, age)
	values
	<foreach collection="list" item="item" index="index" separator=",">
		(#{item.name}, #{item.pwd}, #{item.age} )
	<foreach>
</insert>

Mybatis 插入数据报错

org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.executor.ExecutorException: Error preparing statement. Cause: java.lang.StringIndexOutOfBoundsException: String index out of range: 96

问题原因是执行代码中有批处理操作,但是没有判断要插入的集合是否为空,错误代码:

List<PostTag> newAddTags = new ArrayList<>();
//......
postTagMapper.insertBatch(newAddTags);

还要注意集合可能为空的情况,这里是直接new出来的,所以没有为空的情况。
正确代码:

List<PostTag> newAddTags = new ArrayList<>();
//......
if(newAddTags.size() != 0){
            postTagMapper.insertBatch(newAddTags);
}

附加

Mybatis批量插入数据(SQLServer与MySQL)

nested exception is org.apache.ibatis.executor.ExecutorException: Error preparing statement. Cause: java.lang.StringIndexOutOfBoundsException: String index out of range: 96

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

掘金者说

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值