MyBatis中特殊符号的转义
作者:笑红尘自来也
编写SQL中会用到<,>,,>= 等,但是在mybatis中不可以这么写,与xml文件的元素冲突,所以需要转义,本文主要介绍了MyBatis中特殊符号的转义,主要介绍了两种转义方式,感兴趣的可以了解一下
描述
MyBatis中特殊符号的转义,有两种方式转义。
第一种
| 描述 | 空格 | 小于 | 大于 | 小于等于 | 大于等于 | 与 | 单引号 | 双引号 |
|---|---|---|---|---|---|---|---|---|
| 原符号 | < | > | <= | >= | & | ’ | " | |
| 转义符 | | < | > | <= | >= | & | ' | " |
<select id = "selectUserByAge" resultType="com.test.hiioc.model.UserTable" >
select
id,userName,age
from
userTable
<where>
1 = 1
<if test = "userTable.startDate!=null">
SIGNING_DATE >= #{userTable.startDate}
</if>
<if test = "userTable.endDate != null">
and SIGNING_DATE <= #{userTable.endDate}
</if>
</where>
</select>
在编写MyBatis的XML映射文件时,对于需要在SQL语句中使用的这些特殊字符,应当使用上表中的转义写法。例如,如果你想在<if>标签中使用大于号,你应该这样写:
<if test="value > 10"> ... </if>
这样,当MyBatis解析XML文件时,会将>正确地解释为大于号(>),而不会与XML标签的结束符混淆。
同理,如果需要在SQL语句中使用小于号,应该使用<。例如:
<if test="value < 10"> ... </if>
对于其他特殊字符,如你需要在SQL语句中包含一个字面上的&字符,你应该写成&,以免XML解析器将其误认为是一个实体的开始。
第二种
使用 <![CDATA[>=]]> 进行转义
<select id = "selectUserByAge" resultType="com.test.hiioc.model.UserTable" >
select
id,userName,age
from
userTable
<where>
IS_DELETE = 1
/*时间段查询*/
<if test = "userTable.startDate != null">
and SIGNING_DATE <![CDATA[>=]]> #{userTable.startDate}
</if>
<if test = "userTable.endDate!=null">
and SIGNING_DATE <![CDATA[<=]]> #{userTable.endDate}
</if>
</where>
</select>代码举例2
<if test="demoWay != null and test="demoWay != '' ">
<if test="demoWay == 'equal' ">
<![CDATA[ and demo_str = #{demoStr} ]]> </if>
<if test="demoWay == 'gt' ">
<![CDATA[ and demo_str > #{demoStr} ]]> </if>
<if test="demoWay == 'lt' ">
<![CDATA[ and demo_str < #{demoStr} ]]> </if>
<if test="demoWay == 'gte' ">
<![CDATA[ and demo_str >= #{demoStr} ]]> </if>
<if test="demoWay == 'lte' ">
<![CDATA[ and demo_str <= #{demoStr} ]]> </if>
</if>
代码举例3
SELECT
d.`name` dept,
count( * ) xx_num,
sum( CASE e.result WHEN 1 THEN 1 ELSE 0 END ) qq_num,
sum( CASE e.result WHEN 1 THEN 1 ELSE 0 END )/count( * ) qq_percent,
sum( CASE WHEN e.xx<![CDATA[>= ]]> 90 THEN 1 ELSE 0 END ) qq1,
sum( CASE WHEN e.xx<![CDATA[<= 89 AND e.xx >= ]]> 80 THEN 1 ELSE 0 END ) qq2,
sum( CASE WHEN e.xx<![CDATA[<= 79 AND e.xx >= ]]> 70 THEN 1 ELSE 0 END ) qq3,
sum( CASE WHEN e.xx<![CDATA[<= 69 AND e.xx >= ]]> 60 THEN 1 ELSE 0 END ) qq4,
sum( CASE WHEN e.xx<![CDATA[<= ]]> 59 THEN 1 ELSE 0 END ) qq5
FROM
ee e
注意事项
- 当使用<![CDATA[ ... ]]>时,需要注意不要让]]>出现在你的SQL语句中,因为这是CDATA区块的结束标记。
- 在某些情况下,混合使用CDATA和转义字符可能会使SQL语句更清晰易读,尤其是在SQL语句非常长或复杂时。
到此这篇关于MyBatis中特殊符号的转义的文章就介绍到这了,更多相关MyBatis 特殊符号转义内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
