问题描述:
今天在Mybatis批量插入时出现了一点问题。本来Mybatis批量插入Mysql的操作在Oracle数据库中突然报错了。具体的操作如下:
@Insert({ "<script>",
"insert into tr_wy_proj_mo_rela(PROJECTID,RULE_CONTENT) values ",
"<foreach collection='nelist' index='index' item='item' separator=','>",
"(#{item.projectid,jdbcType=VARCHAR}, #{item.rule_content,jdbcType=VARCHAR})",
"</foreach>",
"</script>" })
void insertShieldProMoRela(@Param(value="nelist") List<Map<String, Object>> nelist);
具体报错如下:
于是上网搜了一些资料,终于找到了原因。
首先先解释一下,上面的批量插入语句最终会翻译成以下语句:
insert into tr_wy_proj_mo_rela(PROJECTID,RULE_CONTENT) values (?, ?) ,(?, ?);
这种语法在MySQL数据库中是支持的,但是在Oracle数据库中却不适用。
可以通过如下方法来解决:
1、去除SQL中values关键字;
2、foreach中的语句需要select...from dual包裹;如下:
select #{item.projectid,jdbcType=VARCHAR}, #{item.rule_content,jdbcType=VARCHAR} from dual
3、foreach中的separator的值要是union all,union all就是对select查询的结果数据进行合并。
最终修改成如下:
@Insert({ "<script>",
"insert into tr_wy_proj_mo_rela(PROJECTID,RULE_CONTENT) ",
"<foreach collection='nelist' index='index' item='item' separator='UNION ALL'>",
"select #{item.projectid,jdbcType=VARCHAR}, #{item.rule_content,jdbcType=VARCHAR} from dual ",
"</foreach>",
"</script>" })
这样就能正常入库了!