Mybatis 处理集合 特殊符号

来源:互联网 发布:java枚举的声明 编辑:程序博客网 时间:2024/05/20 10:51

Mybatis 处理集合 特殊符号

在Mybatis的xml配置中使用集合,主要是用到了foreach动态语句。

foreach的参数:
foreach元素的属性主要有 item,index,collection,open,separator,close。
item表示集合中每一个元素进行迭代时的别名.
index指 定一个名字,用于表示在迭代过程中,每次迭代到的位置.
open表示该语句以什么开始,separator表示在每次进行迭代之间以什么符号作为分隔 符.
close表示以什么结束。


  1. Mybatis生成delete from table where id in(1,2,…,n)语句的查询

我们一般的做法是在方法的参数处指定传入的参数名称,在xml中使用的时候,集合的名称要和方法的Param的名称一致,这样便于阅读和理解,然后是在对应的xml文件中使用foreach循环。

java代码如下:

Integer updateRecommProduct(@Param("recommId") String recommId, @Param("goodsCodes") String[] goodsCodes);

对应的xml代码如下:

<update id="deleteRecommProduct" parameterType="String">        update        t_prefecture_goods_shop set status=2 where        prefecture_id=#{recommId}        and goodscode in        <foreach item="goodsCode" index="index" collection="goodsCodes"            open="(" separator="," close=")">            #{goodsCode}        </foreach>    </update>

以上方法Mybatis会帮我们进行sql注入拦截,Mybatis如果采用#{xxx}的形式设置参数,Mybatis会进行sql注入的过滤。如果采用的是${xxx},Mybatis不会进行sql注入过滤,而是直接将参入的内容输出为sql语句。


大于号(>)小于号(<)的处理

错误示例

select * from test where id>=10 and id<=20

这里会抛出
Error creating document instance. Cause: org.xml.sax.SAXParseException; lineNumber: 74; columnNumber: 17; 元素内容必须由格式正确的字符数据或标记组成。

正确的应该是

select * from test where id&gt;=10 and id&lt;=20

这是因为Mybatis 对特殊字符做了转义处理。所以在使用的时候,也应该注意特殊字符要提前转义。

以下是对照表

转义代码 符号 符号名称 &lt; < 小于号 &gt; > 大于号 &amp; & 和 &apos; ’ 单引号 &quot; “ 双引号
0 0
原创粉丝点击