修复 MyBatis 中空值引起的 SQL 语法错误
背景
最近在查看别人的项目代码时,遇到了一个问题:数据库中的数据为空。在调试过程中,发现问题出现在调用 MyBatis 中的方法:listByIds(Collection<? extends Serializable> idList)。
报错信息
在使用该方法时,IDEA 控制台报错如下:
### Error querying database. Cause: java.sql.SQLSyntaxErrorException: 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 ')' at line 1
...
SQL: SELECT id,yv,title,description,... FROM video WHERE id IN ( )
...
Caused by: java.sql.SQLSyntaxErrorException: 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 ')' at line 1
 
执行sql也报错:
 
 定位了,是sql的问题,查询发现in内传入的参数不能为空
解决办法
- 使用 XML 编写动态 SQL
 
在 MyBatis 中,可以通过编写 XML 映射文件使用动态 SQL。使用动态 SQL 标签(如 <if>, <foreach>)来构建 SQL 查询,根据传入的参数动态生成查询条件。
示例:
<select id="getVideosByIds" parameterType="VideoQuery" resultType="Video">
    SELECT id, yv, title, description
    FROM video
    <where>
        <if test="ids != null and ids.size() > 0">
            AND id IN
            <foreach item="id" collection="ids" open="(" separator="," close=")">
                #{id}
            </foreach>
        </if>
    </where>
</select>
 
- 参数校验
 
在调用方法之前,对传入参数进行校验,确保传入的参数列表不为空。
if (idList != null && !idList.isEmpty()) {
    // 调用 MyBatis 方法
    videoMapper.listByIds(idList);
} else {
    // 处理参数为空的情况
    // ... 可能需要的处理逻辑
}
 
通过以上方式,可以避免空值引起的 SQL 语法错误,并确保在执行查询时传入了有效的参数。



















