Instructions for the use of CDATA tag of sql statement in mybatis

  • 2021-10-15 10:26:06
  • OfStack

sql statement Usage of CDATA tag

CDATA refers to text data that should not be parsed by an XML parser (Unparsed Character Data).

In the XML element, " < "And" & "It is illegal;

" < "Errors are generated because the parser interprets the character as the beginning of the new element;

" & "Errors also occur because the parser interprets the character as the beginning of the character entity;

When writing an sql statement in an mapper file, you encounter a special character, such as: " < ", etc., it is recommended to use < ! [CDATA [sql statement]] > Tag, which wraps the sql statement and is not parsed by the parser;

For example: "pseudocode"


select id from t_article where create_time <![CDATA[ <= ]]> now();

Range query using CDATA [] tag

When using mybatis in the project, the SQL statement is written in the xml mapping file. If you want to query the data that conforms to the range by being greater than or less than or equal to, but if the written SQL statement is similar to 1 > , < The xml file will be escaped when parsing the xml file, but this is not what we want, so we can use it at this time < ![CDATA[]] > Label to solve it.

< ![CDATA[ ]] > What is it? This is XML syntax. Everything inside CDATA is ignored by the parser.

If the text contains a lot of " < "Character < = and " & "Characters--just like code 1, then it's best to put them all in the CDATA widget.

Example:


<select id="findList" resultType="FleeceRecord">
        SELECT * FROM `fleece_record`
        <where>
<if test="naturalLengthStart != null">
                and natural_length<![CDATA[>=]]>#{naturalLengthStart}
            </if>
            <if test="naturalLengthEnd != null">
                and natural_length<![CDATA[<=]]>#{naturalLengthEnd}
            </if>
         </where>

Related articles: