在mybatis的mapper配置文件中,可以利用<foreach>标签实现sql条件的循环,可完成类似批量的sql
mybatis接受的参数分为:(1)基本类型(2)对象(3)List(4)数组(5)Map
无论传哪种参数给mybatis,他都会将参数放在一个Map中:
如果传入基本类型:变量名作为key,变量值作为value 此时生成的map只有一个元素。
如果传入对象: 对象的属性名作为key,属性值作为value,
如果传入List: "list"作为key,这个List是value (这类参数可以迭代,利用<foreach>标签实现循环)
如果传入数组: "array"作为key,数组作为value(同上)
如果传入Map: 键值不变
<foreach>标签的用法:
六个参数:
collection:要循环的集合
index:循环索引
item:集合中的一个元素(item和collection,按foreach循环理解)
open:以什么开始
close:以什么结束
separator:循环内容之间以什么分隔
一、单参数List的类型:
1. Java Mapper接口
public List dynamicForeachTest(List ids);
2. XML
<select id="dynamicForeachTest" parameterType="java.util.List" resultType="Blog"> select * from t_blog where id in <foreach collection="list" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </select>
3. 测试
@Test public void dynamicForeachTest() { SqlSession session = Util.getSqlSessionFactory().openSession(); BlogMapper blogMapper = session.getMapper(BlogMapper.class); List ids = new ArrayList(); ids.add(1); ids.add(3); ids.add(6); List blogs = blogMapper.dynamicForeachTest(ids); for (Blog blog : blogs){ System.out.println(blog); } session.close(); }
二、单参数array数组的类型:
1. Java Mapper接口
public List dynamicForeach2Test(int[] ids);
2. XML
<select id="dynamicForeach2Test" parameterType="java.util.ArrayList" resultType="Blog"> select * from t_blog where id in <foreach collection="array" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </select>
3. 测试
@Test public void dynamicForeach2Test() { SqlSession session = Util.getSqlSessionFactory().openSession(); BlogMapper blogMapper = session.getMapper(BlogMapper.class); int[] ids = new int[] {1,3,6,9}; List blogs = blogMapper.dynamicForeach2Test(ids); for (Blog blog : blogs){ System.out.println(blog); } session.close(); }
三、自己把参数封装成Map的类型
1. Java Mapper接口
public List dynamicForeach3Test(Map params);
2. XML
<select id="dynamicForeach3Test" parameterType="java.util.HashMap" resultType="Blog"> select * from t_blog where title like "%"#{title}"%" and id in <foreach collection="ids" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </select>
3. 测试
@Test public void dynamicForeach3Test() { SqlSession session = Util.getSqlSessionFactory().openSession(); BlogMapper blogMapper = session.getMapper(BlogMapper.class); final List ids = new ArrayList(); ids.add(1); ids.add(2); ids.add(3); Map params = new HashMap(); params.put("ids", ids); params.put("title", "中国"); List blogs = blogMapper.dynamicForeach3Test(params); for (Blog blog : blogs){ System.out.println(blog); } session.close(); }