使用mybatis查询数据库的记录列表会导致:在以下位置发现意外的标记“ IN”

时间:2019-07-09 16:30:05

标签: java sql mybatis

您知道mybatis映射器可能出什么问题吗?

手动运行此SQL,我得到了预期的结果..

SELECT * FROM TABLE_NAME WHERE ID = '304ed0ea-07c1-4261-bb0f-b44036f285e6' AND RUN_ID IN ('be7e0d61-bdb4-4341-ab35-fd5007e99e58');

SQL在我的映射器xml中看起来是一样的..

<select id="selectByIdAndRunIds" parameterType="java.util.HashMap" resultMap="result">
  SELECT * FROM TABLE_NAME
  WHERE ID = #{id} AND RUN_ID IN
  <foreach item="item" collection="runIds" open="(" separator="," close=")">
      #{item}
  </foreach>
</select>

Java ..

public List<SomeObject> selectByIdAndRunIds(final String id, final List<String> runIds) {
    SqlSession session = MyBatisSqlSession.getInstance().getSqlSessionFactory().openSession(true);

    Map<String, Object> input = new HashMap<>();
    input.put("id", id);
    input.put("runIds", runIds);

    List<SomeObject> result = session.selectList("selectByIdAndRunIds", input);

    session.close();
    return result;
}

这是我得到的错误:

### Error querying database.
Cause: com.ibm.db2.jcc.am.SqlSyntaxErrorException: 
An unexpected token "IN" was found following "= ? AND RUN_ID".  
Expected tokens may include:  "<boolean_factor>".. 
SQLCODE=-104, SQLSTATE=42601, DRIVER=4.24.92

1 个答案:

答案 0 :(得分:0)

runIds是一个空列表,即runIds.size() == 0

添加了逻辑,如果runIds.size() == 0

不执行查询