MyBatis 【foreach 批量插入】

1.批量插入 :  insert into student(id,name,classid) values  (null,?,?),(null,?,?),(null,?,?)...

    <insert id="insertMore" >
        insert into student(id,name,classid) values
        <foreach collection="listStu" index="index" item="item" open="" separator="," close="">
            (null,#{item.name},1)
        </foreach>
    </insert>

接口代码:

public void insertMore(Map< String, Object> map);

测试代码:

         SqlSessionFactory sqlSessionFactory = LoadRes.getsSqlSessionFactory();
         SqlSession session = sqlSessionFactory.openSession();
         
         List<Student> listStu = new ArrayList<Student>();
         Student s = new Student();
         s.setName("同学一");
         Student s2 = new Student();
         s2.setName("同学二");
         Student s3 = new Student();
         s3.setName("同学三");
         
         listStu.add(s);
         listStu.add(s2);
         listStu.add(s3);
         
// 最后用 Map 封装 传入 以作【深层引用】 Map
< String, Object> map = new HashMap<String, Object>(); map.put("listStu", listStu); session.getMapper(StudentDao.class).insertMore(map); session.commit();

 

2.动态多条件查询

    <select id="sel_key_cols" resultType="int">
        select count(*) from student where
        <foreach item="item" index="key" collection="map_column" open="" separator="AND" close="">
            ${key} = #{item}
        </foreach>
    </select>

接口代码:

public Integer sel_key_cols(Map< String, Object> map);

测试代码:

         SqlSessionFactory sqlSessionFactory = LoadRes.getsSqlSessionFactory();
         SqlSession session = sqlSessionFactory.openSession();
         
         
         
         Map< String, Object> map_column = new HashMap<String, Object>();
         map_column.put("name", "鸡腿");
         map_column.put("classid", "3");
         
         // 最后  Map 再封装一层    以作【深层调用】
         Map< String, Object> map = new HashMap<String, Object>();
         map.put("map_column", map_column);
         
         int i = session.getMapper(StudentDao.class).sel_key_cols(map);
         
         System.out.println(i);

 

 

posted @ 2014-04-11 10:54  聆听自由  阅读(1130)  评论(0编辑  收藏  举报