MyBatis list Contains MyBatis 动态SQL 判断List Contains

一、情景描述

        在使用MyBatis 动态SQL查询时,有时候需要判断集合中是否有某个元素,若存在则 动态添加某个 表的关联查询 (常见场景:统计的时候,动态添加某个统计项,需要从关联表中查询),不存在,则不进行任何操作。

        在MyBatis 动态SQL中,如何实现呢?

二、代码演示

        1、在Java代码中,有2个类型的list,分别是 字符串strList 和 数字类型的 intList

ArrayList<String> strList = Lists.newArrayList();
strList.add("apple");
strList.add("orange");
strList.add("banana");

ArrayList<Integer> intList = Lists.newArrayList();
intList.add(111);
intList.add(222);
intList.add(333);

        2、字符串strList MyBatis 动态SQL写法儿如下:

<!-- 测试 strList contains 方法 -->
<if test="strList != null and strList.size() > 0 and strList.contains('apple')">
    AND 'apple' = 'apple'
</if>
<if test="strList != null and strList.size() > 0 and strList.contains('orange'.toString())">
    AND 'orange' = 'orange'
</if>
<if test='strList != null and strList.size() > 0 and strList.contains("banana")'>
    AND 'banana' = 'banana'
</if>

        3、数字类型的 intList MyBatis 动态SQL写法儿如下:

<!-- 测试 intList contains 方法 -->
<if test="intList != null and intList.size() > 0 and intList.contains(222)">
    AND 222 = 222
</if>
<if test="intList != null and intList.size() > 0 and intList.contains('333')">
    AND 333 = 333
</if>

 

 

三、总结

        1、MyBatis 动态SQL借助功能强大的基于 OGNL 的表达式,在写动态SQL时,可以把代码直接在Java程序中运行、测试。 Java程序可以满足,动态SQL一般都可以满足。(不确定?)

        2、注意list的contains方法,是判断集合中是否包含某个元素,最终调用的是 indexOf方法,若判断集合中是否包含某个对象,注意要重写equals方法,否则可能会出现不符合预期结果的情况。

 

        3、注意list的contains方法和String类的contains方法进行区分,前者是判断集合中是否包含某个元素,后者是 判断字符串中是否包含某个字符串。 如上述示例中,若动态SQL这样写,条件是不会执行的。

<if test='strList != null and strList.size() > 0 and strList.contains("ban")'>
    AND 'ban' = 'ban'
</if>

参考资料:动态 SQL_MyBatis中文网

更多推荐

MyBatis list Contains MyBatis 动态SQL 判断List Contains