Mybatis使用IN语句查询

一、简介

在SQL语法中如果我们想使用in的话直接可以像如下一样使用:

select * from HealthCoupon where useType in ( '4' , '3' )
但是如果在MyBatis中的使用in的话,像如下去做的话,肯定会报错:
  1. Map<String, Object> selectByUserId(@Param("useType") String useType)
  2.  
  3. <select id="selectByUserId" resultMap="BaseResultMap" parameterType="java.lang.String">
  4. select * from HealthCoupon where useType in (#{useType,jdbcType=VARCHAR})
  5. </select>

其中useType="2,3";这样的写法,看似很简单,但是MyBatis不支持。。但是MyBatis中提供了foreach语句实现IN查询,foreach语法如下:

  1. foreach语句中, collection属性的参数类型可以使:List、数组、map集合
  2. ​ collection: 必须跟mapper.java中@Param标签指定的元素名一样
  3. ​ item: 表示在迭代过程中每一个元素的别名,可以随便起名,但是必须跟元素中的#{}里面的名称一样。
  4.    index:表示在迭代过程中每次迭代到的位置(下标)
  5.    open:前缀, sql语句中集合都必须用小括号()括起来
  6. ​ close:后缀
  7.    separator:分隔符,表示迭代时每个元素之间以什么分隔

正确的写法有以下几种写法:

(一)、selectByIdSet(List idList)

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

  1. List<User> selectByIdSet(List idList);
  2.  
  3. <select id="selectByIdSet" resultMap="BaseResultMap">
  4. SELECT
  5. <include refid="Base_Column_List" />
  6. from t_user
  7. WHERE id IN
  8. <foreach collection="list" item="id" index="index" open="(" close=")" separator=",">
  9. #{id}
  10. </foreach>
  11. </select>

(二)、List<User> selectByIdSet(String[] idList)

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

  1. List<User> selectByIdSet(String[] idList);
  2.  
  3. <select id="selectByIdSet" resultMap="BaseResultMap">
  4. SELECT
  5. <include refid="Base_Column_List" />
  6. from t_user
  7. WHERE id IN
  8. <foreach collection="array" item="id" index="index" open="(" close=")" separator=",">
  9. #{id}
  10. </foreach>
  11. </select>

(三)、参数有多个时

当查询的参数有多个时,有两种方式可以实现,一种是使用@Param("xxx")进行参数绑定,另一种可以通过Map来传参数。

3.1 @Param("xxx")方式

  1. List<User> selectByIdSet(@Param("name")String name, @Param("ids")String[] idList);
  2.  
  3. <select id="selectByIdSet" resultMap="BaseResultMap">
  4. SELECT
  5. <include refid="Base_Column_List" />
  6. from t_user
  7. WHERE name=#{name,jdbcType=VARCHAR} and id IN
  8. <foreach collection="idList" item="id" index="index"
  9. open="(" close=")" separator=",">
  10. #{id}
  11. </foreach>
  12. </select>

3.2 Map方式

  1. Map<String, Object> params = new HashMap<String, Object>(2);
  2. params.put("name", name);
  3. params.put("idList", ids);
  4. mapper.selectByIdSet(params);
  5.  
  6. <select id="selectByIdSet" resultMap="BaseResultMap">
  7. select
  8. <include refid="Base_Column_List" />
  9. from t_user where
  10. name = #{name}
  11. and ID in
  12. <foreach item="item" index="index" collection="idList" open="(" separator="," close=")">
  13. #{item}
  14. </foreach>
  15. </select>
 
原文地址:https://www.cnblogs.com/zhuyeshen/p/11981785.html