使用foreach标签实现数组查询数据
测试:
//根据gid数组查询商品 @Test public void testGoodsByGids(){ GoodsDao mapper = session.getMapper(GoodsDao.class); //当数组为空,即长度为0时,全查 int[] gids = {2,4}; List<Goods> goods = mapper.selGoodsByGids(gids); for (Goods g : goods){ System.out.println("商品"); System.out.println(g); System.out.println("=============="); } }
dao层:
//根据gid数组查询商品 public List<Goods> selGoodsByGids(@Param("gids") int[] gids);
映射文件:
<!--根据gid数组查询商品--> <select id="selGoodsByGids" resultType="Goods"> <include refid="selGoods"></include> <where> <if test="gids.length > 0"> <foreach collection="gids" item="gid" separator="," open="gid in (" close=")"> #{gid} </foreach> </if> </where> </select>
log4j:
DEBUG [main] - ==> Preparing: select * from t_goods WHERE gid in ( ? , ? ) DEBUG [main] - ==> Parameters: 2(Integer), 4(Integer)