foreach

当一个条件中需要多个参数时则需要将多个参数拼接到一起,例如: in, not in

select id="searchProducts" parameterType="products" resultType="products"> select *from products <where> <if test="pname != null"> and pname like '%${pname}%' </if> <if test="cid != null"> and cid = #{cid} </if> <if test="ids != null"> <foreach collection="ids" open="and pid in (" close=")" separator="," item="id" index="i"> #{id} </foreach> </if> </where> </select> <!-- <if test="ids != null"> 这里不仅判断属性是否为空还判断集合中是否有元素 foreache 标签属性说明: 强调:动态sql本质就是在拼接字符串,带着自己拼接sql的思路来编写动态sql会更好理解 collection 要遍历的集合 open 拼接的前缀 close 拼接的后缀 separator 拼接元素之间的分隔符 item 遍历得到的临时变量名 index 当前元素的索引(不常用) -->

测试代码:

@Test public void searchTest(){ SqlSession session = factory.openSession(); ProductsMapper mapper = session.getMapper(ProductsMapper.class); //查询条件对象 Products condition = new Products(); int[] ids = new int[]{1,2,3,4,5,}; condition.setIds(ids); //执行查询 List<Products> product = mapper.searchProducts(condition); System.out.println(product); session.close(); }
原文地址:https://www.cnblogs.com/huaobin/p/14162720.html