首页  ·  知识 ·  编程语言
mybatis中使用in查询时的注意事项
网友  博客园  JAVA  编辑:擎苍   图片来源:网络
当查询的参数只有一个时findByIds(Listids)如果参数的类型是List,则在使用时,collection属性要必须指定为list

1. 当查询的参数只有一个时 

  findByIds(List<Long> ids)

 1.a 如果参数的类型是List, 则在使用时,collection属性要必须指定为 list


 <select id="findByIdsMap" resultMap="BaseResultMap">

         Select

         <include refid="Base_Column_List" />

         from jria where ID in

                  <foreach item="item" index="index" collection="list" 

                         open="(" separator="," close=")">

                        #{item}

                </foreach>

  </select> 


 findByIds(Long[] ids)

 1.b 如果参数的类型是Array,则在使用时,collection属性要必须指定为 array

复制代码

  <select id="findByIdsMap" resultMap="BaseResultMap">

                 select

                 <include refid="Base_Column_List" />

          from jria where ID in

                  <foreach item="item" index="index" collection="array" 

                         open="(" separator="," close=")">

                        #{item}

                </foreach>

  </select> 


2. 当查询的参数有多个时,例如 findByIds(String name, Long[] ids)

 这种情况需要特别注意,在传参数时,一定要改用Map方式, 这样在collection属性可以指定名称

         下面是一个示例


         Map<String, Object> params = new HashMap<String, Object>(2);

        params.put("name", name);

         params.put("ids", ids);

        mapper.findByIdsMap(params);

 <select id="findByIdsMap" resultMap="BaseResultMap">

                 select

                 <include refid="Base_Column_List" />

          from jria where ID in

                  <foreach item="item" index="index" collection="ids" 

                         open="(" separator="," close=")">

                        #{item}

                </foreach>

   </select> 


完整的示例如下:

例如有一个查询功能,Mapper接口文件定义如下方法:

List<Jria> findByIds(Long... ids);

使用 in 查询的sql拼装方法如下:

复制代码

 <select id="findbyIds" resultMap="BaseResultMap">

                 select

                 <include refid="Base_Column_List" />

          from jria where ID in

                  <foreach item="item" index="index" collection="array" 

                         open="(" separator="," close=")">

                        #{item}

                </foreach>

  </select> 


本文作者:网友 来源:博客园
CIO之家 www.ciozj.com 微信公众号:imciow
   
免责声明:本站转载此文章旨在分享信息,不代表对其内容的完全认同。文章来源已尽可能注明,若涉及版权问题,请及时与我们联系,我们将积极配合处理。同时,我们无法对文章内容的真实性、准确性及完整性进行完全保证,对于因文章内容而产生的任何后果,本账号不承担法律责任。转载仅出于传播目的,读者应自行对内容进行核实与判断。请谨慎参考文章信息,一切责任由读者自行承担。
延伸阅读