MyBatis+ORACLE报错总结
最近在公司撸代码的时候使用MyBatis报的一些错误,我对其进行了一些学习和总结,供读者进行参考
批量插入报错:ORA-00933:SQL命令未正确结束
在公司有一个场景是多条数据插入数据库,我使用了list集合的形式进行插入,我第一次写的时候并没有进行报错,因为我在自测的时候并没有考虑到有两条和两条以上的数据插入到表中,来看一下我错误的写法
- Error updating database. Cause: java.sql.SQLSyntaxErrorException: ORA-00933: SQL 命令未正确结束
<insert id="insertExpenseItem" parameterType="List" >
insert into Student values
<foreach collection="list" item="item" separator="," >
(
seq_item.nextval,
#{item.expId},
#{item.type},
#{item.amount},
#{item.itemDesc}
)
</foreach>
</insert>
先看解决方法,正确的代码如下:
<insert id="insertExpenseItem" parameterType="List" >
insert into Student
<foreach collection="list" item="item" separator="UNION ALL" >
SELECT
seq_item.nextval,
#{item.expId},
#{item.type},
#{item.amount},
#{item.itemDesc}
from dual
</foreach>
</insert>
批量插入中需要用到foreach标签,标签中的含义如下:
- item:集合中每一个元素进行迭代时的别名
- index:指定一个名字,用于迭代时每次到达的位置
- collection:根据传入的参数确定值
- open:表示SQL什么时候开始
- separator:表示每次迭代时用什么作为分割符
- close:表示SQL什么时候结束
批量插入的时候就不需要写values了,记得将values去掉
separator的属性值改为UNION ALL,因为在ORACLE中
insert into 表名 values(xxxx,xxxx),(xxxx,xxxx)
这种语法是不会通过的
foreach标签中需要去掉括号,加入select … from dual(select 和from中为需要插入的数值,注意跟字段名一一对应)。
批量更新报错ORA-00933:SQL 命令未正确结束
ORA-00933: SQL 命令未正确结束 / ORA-00933: SQL command not properly ended ;
在对于多条数据更新的时候,我自以为会和批量插入的方式一样,于是就有了下面的代码
<foreach item="item" index="index" collection="list" separator="," >
update Student
set ID= #{item.id},
Name= #{item.NAME,jdbcType=VARCHAR}
where Grade=#{item.grade,jdbcType=VARCHAR}
and Class = #{item.class,jdbcType=VARCHAR}
</foreach>
这行代码会报出命令未正确结束,也就是语法错误了
来看看正确的解决办法:
<update id="StudentInfo">
<foreach item="item" index="index" collection="list" separator=";" open="begin" close=";end;">
update Student
set ID= #{item.id},
Name= #{item.NAME,jdbcType=VARCHAR}
where Grade=#{item.grade,jdbcType=VARCHAR}
and Class = #{item.class,jdbcType=VARCHAR}
</foreach>
</update>
这里与插入不同的地方就是:
- separator=“;” 这里面一定要分号 “;” 而不是逗号","
- begin和end必须要成对出现,而且要以分号结尾,open=“begin"和close=”;end;"也就是为了补全语法
这条更新的SQL也就相当于:
begin
update Student set ID=xxxx and Name = 'xxxx';
update Student set ID=xxxx and Name = 'xxxx';
......
end;
Mybatis返回值为Boolean的问题
在写代码的过程中我需要用到一个返回值为true或者false的返回值,这个值是根据在数据库中根据相关条件查找获取到的,举个栗子:
<select id="isNewBuss" resultType="java.lang.Boolean">
<![CDATA[select count(id)
from User
where PHONE = #{phone}]]>
</select>
Mybatis是根据查询到的记录数进行转换的(1表示为true,0表示为false) 。然而,如果查询到多条记录(大于1),则返回的布尔值为false。
这时候,我们需要将返回来的记录数进行判断,就可以确保该记录在数据库中的唯一性了。