我在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)
答案 0 :(得分:4)
删除<![CDATA[
和]]>
,因为这会转义所有查询,mybatis根本不处理它,因此if
作为查询到数据库的一部分逐字传递。{ / p>
<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>
答案 1 :(得分:0)
CDATA部分用于转义包含字符的文本块,否则这些字符将被视为标记[ORACLE定义]。
有时,我们需要它,特别是当我们有这样的标记的where条件时:&lt;,&gt; ,&lt;&gt;等等。
<![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>
添加它就行,标记问题也可以。