Mybatis执行报错 Error querying database. Cause: com.microsoft.sqlserver.jdbc.SQLServerException: “,”附近有语法错误

Mybatis执行报错:

Error querying database. Cause: com.microsoft.sqlserver.jdbc.SQLServerException: “,”附近有语法错误。
The error may exist in com/xxx/xxx/xxxxxx/dao/XxxMapper.xml
The error occurred while setting parameters
SQL: SELECT name FROM Student WHERE CLASS_ID IN ( SELECT ID FROM CLASS WHERE id IN ( ( 1 , 2 ) ) )
Cause: com.microsoft.sqlserver.jdbc.SQLServerException: “,”附近有语法错误。
uncategorized SQLException for SQL []; SQL state [S0001]; error code [102]; “,”附近有语法错误。; nested exception is com.microsoft.sqlserver.jdbc.SQLServerException: “,”附近有语法错误。

通过异常打印的SQL:

SELECT
	name 
FROM
	Student 
WHERE
	CLASS_ID IN ( SELECT ID FROM CLASS WHERE id IN ( ( 1, 2 ) ) )

整个SQL是正确的语法,但是唯一的问题是子查询的IN多了一层括号IN ( ( 1, 2 ) ),去掉括号执行sql发现能够正确执行,所以问题就是出在这里。

检查Mybatis的代码发现,使用forEach,添加了(),在sql上IN的后边手动也加了(),所以导致了这样的问题。错误的写法如下:

SELECT
	name 
FROM
	Student 
WHERE
	CLASS_ID IN (
        <foreach item="item" collection="cid" separator="," open="(" close=")" index="">
            #{item, jdbcType=BIGINT}
        </foreach>
        )