2014-03-30 67 views
1

我嘗試以下,如果從句中的MyBatis並得到了以下異常,請幫我找出這裏的問題..MyBatis的if語句

public class Student{ 

private Integer studId; 
private String name; 
private String email; 
private Date dob; 
} 

映射

​​

例外,我得到:

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) 

回答

4

刪除<![CDATA[]]>因爲這逃避了所有的查詢和mybat根本不處理它,因此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> 
0

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> 

添加它只是在與標記問題一致也行。