mybatis的使用技巧4——foreach循环和choose选择

9 篇文章 0 订阅
6 篇文章 0 订阅

在实际项目开发中,sql的编写起了关键作用。

如果想复用自定义的多条件查询功能,实现一个sql就能支持大多数的查询,那循环<foreach/>和选择<choose/>标签绝对是一大利器,再配上万能map,绝对值得使用和推荐。

1.存在如下的mapper接口信息(利用万能map动态传参)
List<PlanBudget> diySelectPlanBudgetList(Map<String,Object> params);
2.万能map动态参数举例说明:

  其中currentStr是自定义时间参数,根据自己实际处理,ids是数组。

Map<String,Object> params = new HashMap<>();
String currentStr = DateCommonUtils.DEFAULT_DATETIME_FORMATE.format(new Date());
params.put("endStr",currentStr);
params.put("status_info","00");
params.put("status",1);
params.put("qoutaType","05");
params.put("ids",new int[]{1,3});
3.对应xml的写法:

属性及写法详解:

  • <foreach/>

collection:对应map中的属性名称,也就是map参数中的ids;

item:该参数相当于循环变量,可以任意自定义,但是须与in子句的取值保持一样;

其他参数保存固定写法即可。

  • <choose/>

该标签不能单独使用,须与<when/>标签连用,用法与if判断语句类型,具体可参考如下。

  • 大于,小于的写法

由于xml规范不可以直接使用五个保留字符,“  < > & ” ’  ”

因此在mybaits的xml中,大于或者小于要按照如下规则进行编写:
> 要写成 &gt;
< 要写成 &lt;
>= 要写成 &gt;=
<= 要写成 &lt;=

<select id="diySelectPlanBudgetList" parameterType="map" resultType="com.test.plan.entity.PlanBudget">
        select *
        from plan_budget
        <where>
            del_flag = '0'
            <if test="ids != null and ids.length > 0">
                and id in
                <foreach collection="ids" item="id" open="(" separator="," close=")">
                    #{id}
                </foreach>
            </if>
            <if test="status != null "> and status = #{status}</if>
            <choose>
                <when test="description != null and description != ''">
                    and description = #{description}
                </when>
                <otherwise>
                    and description is null
                </otherwise>
            </choose>
            <choose>
                <when test="status_info != null and status_info == '00'">
                    <if test="startStr != null  and startStr != ''"> and DATE_FORMAT(plan_start,'%Y-%m-%d %H:%i:%s') &lt; #{startStr}</if>
                    <if test="endStr != null  and endStr != ''"> and DATE_FORMAT(plan_end,'%Y-%m-%d %H:%i:%s') &gt; #{endStr}</if>
                </when>
                <when test="status_info != null and status_info == '01'">
                    <if test="endStr != null  and endStr != ''"> and DATE_FORMAT(plan_end,'%Y-%m-%d %H:%i:%s') &lt; #{endStr}</if>
                </when>
            </choose>
        </where>
    </select>

  • 15
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值