Mysql的批量操作(批量查询)

前面几篇Mysql的文章一直在写普通查询,从这篇开始,会写一些Mysql的批量操作。

本篇主要是mysql的批量查询,主要是通过id来查询,如果需要查询多个id对应的多个数据,使用for循环去查,对程序来说不太高效。在这里就可以通过批量循环进行查询。

直接上代码:

java代码部分:

         @Responsebody

         @RequestMapping("/XXX.do")

        public void XXX(ModelMap model ,HttpServletRequest request,HttpServletResponse response) {

                     // 这里是要传到mapper中的集合,集合里面封装的是你要查询的数据的id

                     List<String> idList = new ArrayList<String>

                     idList.add("id1");

                     idList.add("id2");

                     // 创建map的过程就省略了,把封装了id的集合放到你的map集合中

                     map.put("idList",idList);

                     // 把map作为参数传到对应的Mapper中                  

        }

sql语句的写法:

    <select  id = "XXX(方法名)"  parameterType = "hashmap" resultMap = "BaseResultMap">

             select * from table(table写自己的表名称)

             where 1 = 1

             <if  test="state != null and state != ' '  ">

                      and state = #{state,jdbcType = INTEGER}

             </if>

             <if test="number != null and number !=' ' ">

                      and (sjrdh like concat ('%',#{number,jdbcType=VARCHAR},'%')

                      or hgh = #{number,jdbcType=VARCHAR})

             </if>

             and id in

             <foreach collection="idList"  item="item" index ="index" open="(" separator="," close=")">

                        #{item}

             </foreach>

             order by XX(根据某个字段排序) desc

            <if test ="beginIndex != null and beginIndex != -1  ">

                     limit #{beginIndex,jdbcType=INTEGER},#{pageSize,jdbcType=INTEGER}

           </if>

    </select>


该sql语句是根据条件按照某个顺序进行的批量查询,如果只要求批量查询,不根据字段筛选,可以把<if>去掉。其中<foreach>中的collenction的值为map集合中的idList集合的Key值。item是指定List集合中的条目为item,此处表示String类型的id。open,close形式写出来语句以后(id1,id2)这种表现形式


猜你喜欢

转载自blog.csdn.net/little_soybean/article/details/78659864