Mybatis使用foreach语句实现IN查询

  Mybatis使用foreach语句实现IN查询,二话少说,直接上实例。

一.mapper.java

List<User> selectByIdSet(@Param("idList")List<Integer> idList);

 

二.Mapper.xml

<select id="selectByIdSet" resultMap="BaseResultMap">
    SELECT
       <include refid="Base_Column_List" />
    from t_user
      WHERE id IN
      <foreach collection="idList" item="id" index="index" open="(" close=")" separator=",">
        #{id}
      </foreach>
</select>

<select id="selectByPrimaryKeyOnce" parameterType="cn.bijian.dto.entity.CardInfoExt" resultMap="BaseResultMap">
    SELECT
       <include refid="Base_Column_List" />
    from t_user
    <if test="idList!=null and idList.size() >0">
      WHERE id IN
      <foreach collection="idList" item="id" index="index" open="(" close=")" separator=",">
        #{id}
      </foreach>
    </if>
</select>

  log打出的执行时的sql语句:

insert into t_user (id, name, age, sex, create_time) values (?, ?, ?, ?)

 

三.解释说明

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

 

文章来源:https://blog.csdn.net/u013041642/article/details/72823579

posted on 2018-08-14 23:45  bijian1013  阅读(444)  评论(0)    收藏  举报

导航