MyBatis动态SQL中foreach和choose的简单介绍(day22)

最近在学习mybatis,已经学到动态SQL中如何去使用foreach和choose那里了,今天的博客内容就简单的回顾一下今日学习的知识。

一、概述

  动态SQL,是基于OGNL(object graph navigation languang)表达式,完成多条件查询等逻辑实现,用户实现动态SQL的元素主要有:

if、trim、where、set、choose(when、otherwise)、foreach。

二、foreach元素介绍

   foreach是一个迭代集合,通常用于int条件,属性有 item、index、collection:必须指定(list、array、map-key)、open、separator、close。

三、choose(when、otherwise)元素介绍

  choose(when、otherwise)相当于Java中switch语句,当when有条件满足的时候,就跳出choose。

四、代码展示

    foreach的代码展示(collection指定的数组array):

 1 <!--
 2         foreach
 3         数组 array
 4     -->
 5     <select >
 6         select * from smbms_user
 7         <where>
 8             userRole in 
 9             <foreach collection="array" item="roles" separator="," open="(" close=")">
10                 #{roles}
11             </foreach>
12         </where>
13     </select>

  foreach的代码展示(collection指定的集合list):

 1     <!--
 2         foreach
 3         集合 list
 4     -->
 5     <select >
 6         select * from smbms_user
 7         <where>
 8             userRole in 
 9             <foreach collection="list" item="roleList" open="(" separator="," close=")">
10                 #{roleList}
11             </foreach>
12         </where>
13     </select>

  

  foreach的代码展示(collection指定的Map):

1     <select >
2         select * from smbms_user
3         where userName like CONCAT('%',#{userName},'%')
4         and userRole in 
5         <foreach collection="roles" item="role" open="(" separator="," close=")">
6             #{role}
7         </foreach>
8     </select>
 1     <!--
 2         foreach
 3         map  2
 4     -->
 5     <select >
 6         select * from smbms_user
 7         where userName like CONCAT('%',#{user.userName},'%')
 8         and userRole in
 9         <foreach collection="roles" item="role" open="(" separator="," close=")">
10             #{role}
11         </foreach>
12     </select>

五、END

    为了不错过每天的见面,请记得点击一下【关注】啊~

    作者:javagril,00后女生,一个IT界冉冉升起的新星,想带你遨游缤纷多彩的编程世界。