首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MyBatis if子句

MyBatis if子句
EN

Stack Overflow用户
提问于 2014-03-30 14:56:34
回答 2查看 13.9K关注 0票数 2

我尝试遵循MyBatis中的if子句,但得到以下异常,请帮助我识别这里的问题。

代码语言:javascript
复制
public class Student{

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

映射

代码语言:javascript
复制
<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>

我得到的异常:

代码语言:javascript
复制
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)
EN

回答 2

Stack Overflow用户

发布于 2014-03-31 21:19:00

删除<![CDATA[]]>,因为这将转义所有查询,并且mybatis根本不会处理它,因此if将作为数据库查询的一部分逐字传递。

代码语言:javascript
复制
<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>
票数 6
EN

Stack Overflow用户

发布于 2017-09-04 23:58:20

CDATA节用于转义包含字符的文本块,否则这些字符将被视为标记ORACLE定义。

有时,我们需要它,特别是当我们有一个带有<,>,<>等标记的where条件时。

代码语言:javascript
复制
<![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>

将它添加到带有标记问题的行上也是可行的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22741205

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档