我尝试遵循MyBatis中的if子句,但得到以下异常,请帮助我识别这里的问题。
public class Student{
private Integer studId;
private String name;
private String email;
private Date dob;
}映射
<select id="searchStudent" parameterType="hashmap" resultMap="StudentResult">
<![CDATA[
SELECT * FROM STUDENTS
WHERE 1 = 1
<if test="studId != null">
AND STUD_ID= #{studId}
</if>
<if test="name != null">
AND NAME like #{name}
</if>
]]>
</select>我得到的异常:
Exception in thread "main" org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'test="studId != null">
AND STUD_ID= 1
</if>
<if test="name != null">
' at line 4
### The error may exist in StudentMapper.xml
### The error may involve com.maventest.mytest.StudentMapper.searchStudent-Inline
### The error occurred while setting parameters
### SQL: SELECT * FROM STUDENTS WHERE 1 = 1 <if test="studId != null"> AND STUD_ID= ? </if> <if test="name != null"> AND NAME like ? </if>
### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'test="studId != null">
AND STUD_ID= 1
</if>
<if test="name != null">
' at line 4
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:23)发布于 2014-03-31 21:19:00
删除<![CDATA[和]]>,因为这将转义所有查询,并且mybatis根本不会处理它,因此if将作为数据库查询的一部分逐字传递。
<select id="searchStudent" parameterType="hashmap" resultMap="StudentResult">
SELECT * FROM STUDENTS
WHERE 1 = 1
<if test="studId != null">
AND STUD_ID= #{studId}
</if>
<if test="name != null">
AND NAME like #{name}
</if>
</select>发布于 2017-09-04 23:58:20
CDATA节用于转义包含字符的文本块,否则这些字符将被视为标记ORACLE定义。
有时,我们需要它,特别是当我们有一个带有<,>,<>等标记的where条件时。
<![CDATA[ SELECT * FROM STUDENTS WHERE 1 = 1 ]]>
<if test="studId != null">
<![CDATA[ AND STUD_ID= #{studId} ]]>
</if>
<if test="name != null">
**<![CDATA[ AND COD_PER <> 'ASSU' ]]>**
</if>
将它添加到带有标记问题的行上也是可行的。
https://stackoverflow.com/questions/22741205
复制相似问题