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 特殊符号转义内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
SpringBoot解决406错误之返回对象缺少Getter/Setter方法引发的问题
在Spring Boot开发中,接口请求返回数据是系统交互的重要环节,然而,开发过程中常常会遇到由于数据类型或返回格式问题导致的错误,其中最常见的就是406 Not Acceptable异常,本篇文章以实际的案例出发,详细分析在POST请求中产生406错误的原因2024-11-11
Mybatis 在 insert 插入操作后返回主键 id的操作方法
这篇文章主要介绍了Mybatis 在 insert 插入操作后返回主键 id的操作方法,本文结合示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2022-12-12


最新评论