gpt4 book ai didi

MyBatis if 子句

转载 作者:行者123 更新时间:2023-12-02 01:05:44 29 4
gpt4 key购买 nike

我尝试在 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)

最佳答案

删除 <![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>

关于MyBatis if 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22741205/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com