作业4,5,6
上代码;
DemoMapper接口:
/** * 通过商品id修改商品名 * @param map * @return */ Integer updateGoods_nameById(Map<String,String > map);
DemoMapper.xml:
<update id="updateGoods_nameById"> UPDATE goods <trim prefix="set" suffix="WHERE goods_id = #{userId}"> <if test="userName!=null and userName !=''"> goods_name = #{userName} </if> </trim> </update>
效果:
------------------------------------------------------------------------
直接上代码:
DemoMapper接口;
/**
* 通过数组传参 foreach遍历查询信息
* @param its
* @return
*/
List<Goods> getGoodsListBy_in(Integer [] its);
DemoMapper.xml:
</select> <select id="getGoodsListBy_in" resultType="com.pojo.Goods"> SELECT * FROM goods where goods_id in <foreach collection="array" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </select>
测试类:
@Test public void test04(){ SqlSession sqlSession = MyBatisUtil.createSqlSession(); DemoMapper mapper = sqlSession.getMapper(DemoMapper.class); // Map<String,String> map = new HashMap<String, String>(); Integer [] its = {1,2,3}; List<Goods> list = mapper.getGoodsListBy_in(its); for (Goods goods : list) { System.out.println(goods.getGoods_code()+" "+goods.getGoods_name()); } MyBatisUtil.closeSqlSession(sqlSession); }
测试结果:
--------------------------------------------------------------------------------------
直接上代码:
接口:
/** * 使用Map集合传参,通过foreach遍历查询信息 * @return */ List<Goods> getGoodsListBy_map(Map<String,Object> map);
xml:
<select id="getGoodsListBy_map" resultType="com.pojo.Goods"> SELECT * FROM goods where goods_id in
这里的collection是相当于Map的key 我们要通过这个key找到对应的集合然后遍历,所以这里的collection = 测试的its---- key; <foreach collection="its" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </select>
测试类:
@Test public void test05(){ SqlSession sqlSession = MyBatisUtil.createSqlSession(); DemoMapper mapper = sqlSession.getMapper(DemoMapper.class); Map<String,Object> map = new HashMap<String, Object>(); List<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); list.add(3); map.put("its",list); List<Goods> goodsListBy_map = mapper.getGoodsListBy_map(map); for (Goods goods : goodsListBy_map) { System.out.println(goods.getGoods_code()+" "+goods.getGoods_name()); } MyBatisUtil.closeSqlSession(sqlSession); }
测试结果: