当前位置:   article > 正文

MyBatis的foreach语句详解_mybatis foreach

mybatis foreach

foreach 属性介绍

foreach 用于迭代传入过来的参数。 
它的属性介绍分别是

  • 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” 
    • 如果传入的是单参数且参数类型是一个 List 的时候,collection 属性值为 list
    • 如果传入的是单参数且参数类型是一个 array 数组的时候,collection 的属性值为 array
    • 如果传入的参数是多个的时候,我们就需要把它们封装成一个 Map 了,当然单参数也可以封装成 map。
  • item: 循环体中的具体对象。支持属性的点路径访问,如 item.age,item.info.details。具体说明:在 list 和数组中是其中的对象,在 map 中是 value,该参数为必选。(它是每一个元素进行迭代时的别名)
  • index:在 list 和数组中,index 是元素的序号;在 map 中,index 是元素的 key。
  • open:表示该语句以什么开始
  • close:表示该语句以什么结束
  • separator:表示在每次进行迭代之间以什么符号作为分隔符

介绍完属性之后,下面就进入实践。首先先来看一个简单到爆炸的表(表名:t_test_foreach)

这里写图片描述

  1. 1)array
  2. List<CarnumberAlarm> selectByDeviceIdAndTime(String[] ids);
  3. xml配置:
  4. <if test="ids != null and ids.length > 0" >
  5. deviceId in
  6. <foreach collection="array" open="(" separator="," close=")" item="item" index="index">
  7. #{item,jdbcType=VARCHAR}
  8. </foreach>
  9. </if>
  10. 2)list
  11. List<CarnumberAlarm> selectByDeviceIdAndTime(List<String> ids);
  12. xml配置:
  13. <if test="ids != null and ids.size() > 0" >
  14. deviceId in
  15. <foreach collection="list" open="(" separator="," close=")" item="item" index="index">
  16. #{item,jdbcType=VARCHAR}
  17. </foreach>
  18. </if>
  19. <!--list<String>-->
  20. <select id="getSocketNumList" parameterType="com.ex.application.model.dto.ScoketNumDTO" resultType="com.ex.application.model.dto.ScoketNumDTO">
  21. select sn,station_sn,socket_number,member_sn,state from socket where 1=1
  22. <if test="station_sn != null and station_sn != ''">
  23. station_sn = #{station_sn}
  24. </if>
  25. <if test="station_sns != null and station_sns.size() > 0" >
  26. and station_sn in
  27. <foreach collection="station_sns" open="(" separator="," close=")" item="item" index="index">
  28. #{item,jdbcType=VARCHAR}
  29. </foreach>
  30. </if>
  31. </select>
  32. 3map
  33. List<CarnumberAlarm> selectByDeviceIdAndTime(Map<String, Object> params);
  34. xml配置:
  35. <if test="ids != null and ids.size() > 0" >
  36. deviceId in
  37. <!--collection属性是map.key,其它所有属性都是map.key-->
  38. <foreach collection="ids" open="(" separator="," close=")" item="item" index="index">
  39. #{item,jdbcType=VARCHAR}
  40. </foreach>
  41. </if>

单参数是 array /list类型

  1. <delete id="deleteByList">
  2. delete from goods where id in
  3. <foreach collection="list" open="(" separator="," close=")" item="haha">
  4. #{haha}
  5. </foreach>
  6. </delete>
  7. //批量操作 (返回影响了几条数据的一个int 数字)
  8. public Integer deleteByList(List<GoodsInfo> list);

测试类

  1. // ids = {1,2,3}
  2. public List<User> testFindByArray(int[] ids) throws Exception {
  3. SqlSession sqlSession = getSession().openSession();
  4. userList = sqlSession.selectList(NameSpace + ".findByArray", ids);
  5. System.out.println(userList.toString());
  6. sqlSession.close();
  7. return userList;
  8. }

mapper.xml

  1. <!--这里的 item 值可以和传递过来的参数名不一样,在介绍属性的时候已经说过这是一个别名了。比如可以修改成如下代码:
  2. <foreach collection="array" item="id" index="index" open="(" close=")" separator=",">
  3. #{id} <!--这里要和 item 值保持一致-->
  4. </foreach>
  5. -->
  6. <select id="findByArray" resultType="com.test.foreach.User">
  7. SELECT id,`name` FROM t_test_foreach WHERE id IN
  8. <foreach collection="array" item="ids" index="index" open="(" close=")" separator=",">
  9. #{ids}
  10. </foreach>
  11. </select>

输出结果

  1. DEBUG - ==> Preparing: SELECT id,`name` FROM t_test_foreach WHERE id IN ( ? , ? , ? )
  2. DEBUG - ==> Parameters: 1(Integer), 2(Integer), 3(Integer)
  3. DEBUG - <== Total: 3
  4. [User{name='n1', id='1'}, User{name='n2', id='2'}, User{name='n3', id='3'}]

单参数是 List 类型

测试类

  1. // List 元素有 135
  2. public List<User> testFindByList(List<Integer> ids) throws Exception {
  3. SqlSession sqlSession = getSession().openSession();
  4. userList = sqlSession.selectList(NameSpace + ".findByList", ids);
  5. System.out.println(userList.toString());
  6. sqlSession.close();
  7. return userList;
  8. }

mapper.xml

  1. <select id="findByList" resultType="com.test.foreach.User">
  2. SELECT id,`name` FROM t_test_foreach WHERE id IN
  3. <foreach collection="list" item="ids" index="index" open="(" close=")" separator=",">
  4. #{ids}
  5. </foreach>
  6. </select>

输出结果

  1. DEBUG - ==> Preparing: SELECT id,`name` FROM t_test_foreach WHERE id IN ( ? , ? , ? )
  2. DEBUG - ==> Parameters: 1(Integer), 3(Integer), 5(Integer)
  3. DEBUG - <== Total: 3
  4. [User{name='n1', id='1'}, User{name='n3', id='3'}, User{name='n5', id='5'}]

单参数是 Map 类型

测试类

  1. // Map<String, Object> 中的元素有 int[] ids = {2, 4};map.put("ids", ids);
  2. public List<User> testFindByMap(Map map) throws Exception {
  3. SqlSession sqlSession = getSession().openSession();
  4. System.out.println(map.toString());
  5. List<Object> objects = sqlSession.selectList(NameSpace + ".findByMap", map);
  6. System.out.println(objects.toString());
  7. sqlSession.close();
  8. return userList;
  9. }

mapper.xml

  1. <!--注意 collection 值是 ids,即要进行迭代的对象。觉得有点懵的伙伴可以回到最开始介绍 collection 属性那里看看,不要急-->
  2. <select id="findByMap" resultType="com.test.foreach.User">
  3. SELECT id,`name` FROM t_test_foreach WHERE id IN
  4. <foreach collection="ids" item="id" index="index" open="(" close=")" separator=",">
  5. #{id}
  6. </foreach>
  7. </select>

输出结果

  1. DEBUG - ==> Preparing: SELECT id,`name` FROM t_test_foreach WHERE id IN ( ? , ? )
  2. DEBUG - ==> Parameters: 2(Integer), 4(Integer)
  3. DEBUG - <== Total: 2
  4. [User{name='n2', id='2'}, User{name='n4', id='4'}]

多参数

这种情况在传参数时,一定要改用 Map 方式

测试类

  1. public void testUpdateByParams(int[] ids,String name) throws Exception {
  2. SqlSession sqlSession = getSession().openSession();
  3. Map<String,Object> map = new HashMap<String, Object>();
  4. map.put("ids",ids); // ids = {1,2,4}
  5. map.put("name",name);// name = "updated"
  6. sqlSession.selectList(NameSpace + ".findByParams", map);
  7. sqlSession.close();
  8. }

mapper.xml

  1. <select id="findByParams">
  2. UPDATE t_test_foreach SET `name` = '#{name}' WHERE id IN
  3. <foreach collection="ids" item="item" index="index" open="(" close=")" separator=",">
  4. #{item}
  5. </foreach>
  6. </select>

输出结果

  1. DEBUG - ==> Preparing: UPDATE t_test_foreach SET `name` = ? WHERE id IN ( ? , ? , ? )
  2. DEBUG - ==> Parameters: updated(String), 1(Integer), 2(Integer), 4(Integer)

这里写图片描述

尊重他人劳动成果,转载请注明出处: 
mybatis foreach 属性及其三种使用情况_mybatis foreach object-CSDN博客

参考文章: 
Mybatis 示例之 foreach (上)_mybatis的foreach-CSDN博客 
MyBatis的foreach语句详解-CSDN博客

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/749024?site
推荐阅读
相关标签
  

闽ICP备14008679号