mybatis使用foreach处理List中的Map mybatis-----传入传出多个参数,都是map或list,批量更新
https://nannan408.iteye.com/blog/2170470
https://blog.csdn.net/xingzhishen/article/details/86424395
参数的数据结构是一个ArrayList<Map<String, Integer>>,需要以String,Integer为条件批量更新数据库的数据.
将参数封装到叫做JsonData的qv中,JsonData的关键代码是
private ArrayList<Map<String, Integer>> usersPlatforms;
public ArrayList<Map<String, Integer>> getUsersPlatforms() {
return usersPlatforms;
}
public void setUsersPlatforms(ArrayList<Map<String, Integer>> usersPlatforms) {
this.usersPlatforms = usersPlatforms;
}
Mapper中的方法是:
updateXxxx(JsonData jsonData);
Mapper.xml的sql是:
<update id="updateXxxx" parameterType="JsonData">
UPDATE xxx SET `xx` = 10
<where>
<foreach collection="usersPlatforms" item="userPlatform" open="" close="" separator="OR">
<foreach collection="userPlatform.keys" item="key" open=" user_id = " close="" separator="">
#{key}
</foreach>
<foreach collection="userPlatform.values" item="value" open=" AND platform = " close="" separator="">
#{value}
</foreach>
</foreach>
</where>
</update>
----------------------------------- ----------------------------------- ----------------------------------- -----------------------------------
1.前言.
如题.
2.代码.
(1)mapper.xml.
- <select id="getTest" resultType="java.util.HashMap" parameterType="java.util.HashMap" >
- select count(1) as c1,userid as c2 from test where insertime <![CDATA[>=]]> #{beginTime,jdbcType=TIMESTAMP} and insertime <![CDATA[<]]> #{endTime,jdbcType=TIMESTAMP} group by userid
- </select>
(2)interface
- public interface TestMapper{
- List<Map<String,Object>> getTest(Map<String,Object> map);
- }
(3)
测试类:
- @Test
- public void test3(){
- SimpleDateFormat sf=new SimpleDateFormat("yyyyMMddHH");
- Date d1 = null;
- try {
- d1 = sf.parse("2014061100");
- } catch (ParseException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- Date d2 = null;
- try {
- d2 = sf.parse("2014121100");
- } catch (ParseException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- //new
- Map map=new HashMap<String, Object>();
- map.put("beginTime", d1);
- map.put("endTime", d2);
- List list=testMapper.getTest(map);
- System.out.println(list.size());
- }
2.批量更新.
大部分传list就可以了,传map也可以,但map也要解析成list,可以自行研究map,这里介绍通用的list传值方法:
(1)mapper
- public int batchUpdate(List<Test> list);
(2)xml
- <update id="batchUpdate" parameterType="java.util.List">
- <foreach collection="list" item="list" index="index" open="begin" close=";end;" separator=";">
- update Test
- <set>
- A= A + #{list.a}
- </set>
- where B = #{list.b}
- </foreach >
- </update>
(3)测试类
- public void testBatchUpdate(){
- List<Test > item=new ArrayList<Test>();
- for(int i=0;i<10;i++){
- Test Test=new Test();
- Test.setA(i+10);
- Test.setB("kkk");
- item.add(Test);
- }
- int count= TestMapper.batchUpdate(item);
- System.out.println("jieguo:"+ count);
- }