mybatis 关于 传入参数为集合list和map的写法

来源:互联网 发布:如何弄死一个淘宝店铺 编辑:程序博客网 时间:2024/06/05 22:39

1、mybatis 中foreach的用法

foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。foreach元素的属性主要有item,index,collection,open,separator,close。item表示集合中每一个元素进行迭代时的别名,index指定一个名字,用于表示在迭代过程中,每次迭代到的位置,open表示该语句以什么开始,separator表示在每次进行迭代之间以什么符号作为分隔符,close表示以什么结束。

使用 foreach 时特别要注意这个属性,不同的条件下这个值是不一样的

(1)、当传入的参数为list的时候,collection属性值为list

(2)、当传入的参数为array,collection的属性值为array 

例如,当传入的参数为 list的时候

 <select id="selectUserByUserIdList" parameterType="java.util.List" resultMap="BaseResultMap">
select * from user_user_t  where 
<if test="list!= null">
user_id in
<foreach item="item" index="index" collection="list"  open="("
separator="," close=")">
#{item}
</foreach>
</if>
</select> 

当传入的参数为array的时候

<select id="selectUserByUserIdList" parameterType="java.util.List" resultMap="BaseResultMap">
select * from user_user_t  where 
<if test="list!= null">
user_id in
<foreach item="item" index="index" collection="array"  open="("
separator="," close=")">
#{item}
</foreach>
</if>
</select> 

2、当传入的参数为map的时候

比如 Map<String, Object> map=new HashMap<>();

map.put("userName",name);

map.put("userPhoto", photo);

那么在mybatis中怎样写呢

<select id="selectUserByParams"       parameterType="Map" resultMap="BaseResultMap">
select * from user_user_t  where  user_name=#{userName ,jdbcType=VARCHAR} and user_photo=#{userPhoto,jdbcType=VARCHAR}
</select>

3、当传入的参数为map,并且map的key为list,那么在mybatis中又该怎么写呢

例如: List<String> label=new ArrayList<>;

 label.add("ky");         label.add("gt") 

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

map.put("labelList", label);

 <select id="selectProCustomerInqueryByParams" parameterType="Map" resultMap="BaseResultMap">
  select * from pro_customer_inquery_t where 
  
  <if test="labelList!=null andlabelList.size() != 0">
 
 ( 
  <foreach collection="labelList" item="value"  index="index"
  
 <if test="(index+1)==labelList.size()">
    content=#{value,jdbcType=VARCHAR}) and 
  </if> 
 <if test="(index+1)!=labelList.size()"> 
    content=#{value,jdbcType=VARCHAR} or 
   </if> 
  </foreach>
  </if>
 is_delect=1 and is_done=1 and customer_user_id=#{userId,jdbcType=INTEGER}  group by user_id
  </select>

特别要注意用红色标注的地方,这里使用了动态的sql。加括号是为了让这个字段合并为一个条件。如果不加括号查出来的结果就会不一样,不信可以试一下。写的不好的地方请谅解!

1 0
原创粉丝点击