因此,我试图通过Mybatis动态生成SQL语句的WHERE子句。我有一个HashMap,其中的键是列名,而值是具有以下格式的Object []:{运算符,value1,value2}。我的Mybatis Mapper中有以下内容:
WHERE
<foreach item="colArgs" index="colName" collection="whereMap.entrySet()" open="(" separator=" AND " close=")">
<bind name="operator" value="colArgs[0]" />
<bind name="value1" value="colArgs[1]" />
<bind name="value2" value="colArgs[2]" />
<if test="colArgs[0] == ' BETWEEN ' ">
${colName} ${operator} #{value1} AND #{value2}
</if>
<if test="colArgs[0] != ' BETWEEN ' ">
${colName} ${operator} #{value1}
</if>
</foreach>
当我传递以下HashMap时:
{"colName1", {" = ", "foo", ""}}, {"colName2", {" BETWEEN ", 1, 2}}
我希望:
WHERE (colName1 = "foo") AND (colName2 BETWEEN 1 AND 2)
但是MyBatis将其解释为以下内容:
WHERE (colName1 = 1) AND (colName2 BETWEEN 1 AND 2)
即使我删除并直接使用#{colArgs [1]},同样的问题仍然存在。有趣的是,$ {operator} / $ {colArgs [0]}可以按预期工作。不幸的是,不能使用$代替#,因为这会导致类型与不同类型的列不匹配(例外:Cause: org.postgresql.util.PSQLException: ERROR: operator does not exist: character varying = integer
)。
我对MyBatis来说还比较陌生,尤其是Dynamic SQL的东西,因此对识别我做错了的任何帮助将不胜感激。