zoukankan      html  css  js  c++  java
  • 《《《 mybatis的foreach用法(xml中in)

    转载地址:https://www.cnblogs.com/fnlingnzb-learner/p/10566452.html

    使用场景:在一个user表中查询出包含不同的id,前端传参id个数不确定

     1 <select id="selectUser">
     2   select * from user
     3 <!--where条件-->
     4  <where>
     5 <!--判断是否为空-->
     6   <if test="id !=null and id.size>0">
     7      id in 
     8 <!--进行foreacd遍历-->
     9       <foreach collection="id" index="index" item="item" open="(" separator="," close=")">
    10            #{item}
    11       </foreach>
    12   </if>
    13  </where>
    14 </select>

    说明:

    user:表名
    collection:传的参数
    index:在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选
    item:集合中元素迭代时的别名,该参数为必选
    open:foreach代码的开始符号 ————> "("
    separator:元素之间的分隔符————> 例如在in()的时候是逗号 ,
    close:foreach代码的结束符号————> ")"

    具体说明:

    在做mybatis的mapper.xml文件的时候,我们时常用到这样的情况:动态生成sql语句的查询条件,这个时候我们就可以用mybatis的foreach了

    foreach元素的属性主要有item,index,collection,open,separator,close。

    • item:集合中元素迭代时的别名,该参数为必选。
    • index:在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选
    • open:foreach代码的开始符号,一般是(和close=")"合用。常用在in(),values()时。该参数可选
    • separator:元素之间的分隔符,例如在in()的时候,separator=","会自动在元素中间用“,“隔开,避免手动输入逗号导致sql错误,如in(1,2,)这样。该参数可选。
    • close: foreach代码的关闭符号,一般是)和open="("合用。常用在in(),values()时。该参数可选。
    • collection: 要做foreach的对象,作为入参时,List对象默认用"list"代替作为键,数组对象有"array"代替作为键,Map对象没有默认的键。当然在作为入参时可以使用@Param("keyName")来设置键,设置keyName后,list,array将会失效。 除了入参这种情况外,还有一种作为参数对象的某个字段的时候。举个例子:如果User有属性List ids。入参是User对象,那么这个collection = "ids".如果User有属性Ids ids;其中Ids是个对象,Ids有个属性List id;入参是User对象,那么collection = "ids.id"

    在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况下,该属性的值是不一样的,主要有一下3种情况: 

    • 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list .
    • 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array .
    • 如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map,实际上如果你在传入参数的时候,在MyBatis里面也是会把它封装成一个Map的,map的key就是参数名,所以这个时候collection属性值就是传入的List或array对象在自己封装的map里面的key.

    针对最后一条,我们来看一下官方说法:

    注意 你可以将一个 List 实例或者数组作为参数对象传给 MyBatis,当你这么做的时候,MyBatis 会自动将它包装在一个 Map 中并以名称为键。List 实例将会以“list”作为键,而数组实例的键将是“array”。

    所以,不管是多参数还是单参数的list,array类型,都可以封装为map进行传递。如果传递的是一个List,则mybatis会封装为一个list为key,list值为object的map,如果是array,则封装成一个array为key,array的值为object的map,如果自己封装呢,则colloection里放的是自己封装的map里的key值。

    使用方法

    1.单参数List 类型

    1 <select id="countByUserList" resultType="_int" parameterType="list">
    2 select count(*) from users
    3   <where>
    4     id in
    5     <foreach collection="list" index="" item="item" open="(" separator="," close=")">
    6       #{item.id, jdbcType=NUMERIC}
    7     </foreach>
    8   </where>
    9 </select>

    对应的测试代码:

     1 @Test
     2   public void shouldHandleComplexNullItem() {
     3     SqlSession sqlSession = sqlSessionFactory.openSession();
     4     try {
     5       Mapper mapper = sqlSession.getMapper(Mapper.class);
     6       User user1 = new User();
     7       user1.setId(2);
     8       user1.setName("User2");
     9       List<User> users = new ArrayList<User>();
    10       users.add(user1);
    11       users.add(null);
    12       int count = mapper.countByUserList(users);
    13       Assert.assertEquals(1, count);
    14     } finally {
    15       sqlSession.close();
    16     }
    17   }

    2.单参数array数组的类型:

    1 <select id="dynamicForeach2Test" resultType="Blog">
    2      select * from t_blog where id in
    3      <foreach collection="array" index="index" item="item" open="(" separator="," close=")">
    4           #{item}
    5      </foreach>
    6 </select>

    上述collection为array,对应的Mapper代码:
    public List dynamicForeach2Test(int[] ids);
    对应的测试代码:

     1 @Test
     2  public void dynamicForeach2Test() {
     3          SqlSession session = Util.getSqlSessionFactory().openSession();
     4          BlogMapper blogMapper = session.getMapper(BlogMapper.class);
     5          int[] ids = new int[] {1,3,6,9};
     6          List blogs = blogMapper.dynamicForeach2Test(ids);
     7          for (Blog blog : blogs)
     8          System.out.println(blog);
     9          session.close();
    10  }

    3.自己把参数封装成Map的类型

    1 <select id="dynamicForeach3Test" resultType="Blog">
    2          select * from t_blog where title like "%"#{title}"%" and id in
    3           <foreach collection="ids" index="index" item="item" open="(" separator="," close=")">
    4                #{item}
    5           </foreach>
    6  </select>

    上述collection的值为ids,是传入的参数Map的key,对应的Mapper代码:
    public List dynamicForeach3Test(Map params);
    对应测试代码:

     1 @Test
     2     public void dynamicForeach3Test() {
     3         SqlSession session = Util.getSqlSessionFactory().openSession();
     4          BlogMapper blogMapper = session.getMapper(BlogMapper.class);
     5           final List ids = new ArrayList();
     6           ids.add(1);
     7           ids.add(2);
     8           ids.add(3);
     9           ids.add(6);
    10          ids.add(7);
    11          ids.add(9);
    12         Map params = new HashMap();
    13          params.put("ids", ids);
    14          params.put("title", "中国");
    15         List blogs = blogMapper.dynamicForeach3Test(params);
    16          for (Blog blog : blogs)
    17              System.out.println(blog);
    18          session.close();
    19      }

    注意注意sql语句SELECT * FROM ny_jobs WHERE id IN () 这个会报错,所以最后判断一下Ids是有元素的

  • 相关阅读:
    SQL Server(00):JSON 函数
    Oracle(00):SQL Developer官方工具 初探
    SQL Server(00):搜索特定的对象
    三星平板SM-T320刷机
    SQL Server(00):聚合函数
    SQL Server(00):日期时间函数
    SQL Server(00):字符串函数
    SQL Server(00):文本和图像函数
    SQL Server(00):数学函数
    SQL Server(00):元数据函数
  • 原文地址:https://www.cnblogs.com/lidar/p/14230211.html
Copyright © 2011-2022 走看看