MyBatis:动态where条件

MyBatis: dynamic where condition

我是 myBatis 的新手,我需要在查询中添加 where 语句。

我的映射器是这样定义的:

<select id="findMyTableByWhereCondition" parameterType="map" resultMap="mytable">
   SELECT *
   FROM mytable m 
   <where>#{whereCondition}</where>
</select>

我的道:

public List<MyTalbe> findMyTableByWhereCondition(String whereCondition) {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("whereCondition", "m.name = 'Test' and m.surname= 'Test'");
        return sqlSession.selectList("findMyTableByWhereCondition", param );
    }

当我尝试执行此查询时,我得到“无效的关系运算符”。处理此类查询的最佳做法是什么?我需要将它替换为“where”,因为这可能会经常更改,甚至可能非常复杂。

提前致谢

尝试使用${...}引用参数whereCondition:

<select id="findMyTableByWhereCondition" parameterType="map" resultMap="mytable">
   SELECT *
   FROM mytable m 
   <where>${whereCondition}</where>
</select>

文档写道:

By default, using the #{} syntax will cause MyBatis to generate PreparedStatement properties and set the values safely against the PreparedStatement parameters (e.g. ?). While this is safer, faster and almost always preferred, sometimes you just want to directly inject an unmodified string into the SQL Statement. For example, for ORDER BY, you might use something like this:
ORDER BY ${columnName}
Here MyBatis won't modify or escape the string.

注意:使用$会造成SQL注入攻击,最好阅读Dynamic SQL 来自官方文档并尝试构建 sql 那样。