主要不同在于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);
}