MyBatis list Contains MyBatis 动态SQL 判断List Contains

本文介绍了如何在MyBatis动态SQL中使用ListContains方法来判断集合是否包含特定元素,并根据判断结果动态添加SQL查询条件。通过示例展示了针对字符串和数字类型列表的用法,并强调了equals方法的重要性。同时提醒注意ListContains与String类contains方法的区别,以及在实际应用中的潜在问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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中文网

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值