Talk about the representation that sql statement is not equal in Mybatis
- 2021-10-27 07:09:17
- OfStack
Representation of Mybatis sql statement not equal
If you write directly
select * from user where id <> 217;
mybatis reports a syntax error, < > Special characters need to be escaped
As follows
select * from user where id <> 217;
When using Mybatis, special characters need to be escaped, such as
& lt; & gt; < >
& amp; &
& apos; '
& quot; "
Summary of Mybatis Special Symbols (greater than, less than, not equal to) and Common Functions
1. Use scenarios
Because we often use more than ( > , > =), less than ( < , < =), not equal to ( < > ,! =) symbol. Because this symbol contains angle brackets, Mybatis uses the *. xml file format. So
Need inner angle brackets for related escape or use CDATA section.
2. Implementation mode
2.1. Escape special symbols
Note: Strictly speaking, only characters "in XML" < "And" & "It is illegal. Ellipses, quotation marks, and greater than signs are legal, but it is a good practice to replace them with entity references.
符号 | 原符号 | 替换符号 |
---|---|---|
小于 | < | < |
小于等于 | <= | <= |
大于 | > | > |
大于等于 | >= | >= |
不等于 | <> | <> |
与 | & | & |
单引号 | ' | ' |
双引号 | " | " |
mapper file writing:
select * form tablenme t where t.code <> 1
2.2. Use the CDATA section
The text in all XML documents is parsed by the parser. Only text in the CDATA section (CDATA section) is ignored by the parser.
Greater than or equal to < ![CDATA[ > = ]] >
Less than or equal to < ![CDATA[ < = ]] >
Not equal to < ![CDATA[ < > ]] >
mapper file writing:
select t.* form tablenme t where t.code <![CDATA[<>]]> 1
3. Mybatis if judgment is equal to 1 string
When the value of the incoming type is note, the sql in the if judgment will not be executed.
<if test="type=='note'">
and status = 0
</if>
mybatis is resolved using the OGNL expression. In the expression of OGNL, 'note' is resolved to characters, because java is strongly typed, and char and one String will cause inequality. Therefore, sql in if tag will not be resolved.
To solve this problem, just modify the code to:
<if test='type=="note"'> // Note that it is double quotation marks, not single quotation marks! ! !
and status = 0
</if>
4. mysql2 is converted into a string
SELECT cast(fieldName as CHAR) FROM tablename