mysql的foreach使用

来源:互联网 发布:淘宝卖家怎么看总收入 编辑:程序博客网 时间:2024/06/06 03:55

1.  对于 需要 使用mybatis的foreach功能生成的 批量操作语句

比如:   select * from  user  n where ( ? in n.tags , ? in n.tags   ) 

    分解 在mybatis的xml文件就是

       <select id= param= resultmap=>

                select * from user m where

                   <foreach collection="listTag" index="index" item="tag" open="("
                                        separator="," close=")">
                                              #{tag} in n.tags
                                 </foreach>                     

          </select>

2.扩展中: collection: 

    1. 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list

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

    2. 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array

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

    3. 如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可

   

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

  

 3. 

sql语句是这样:

                                  select * from t_news n where ? in n.tags or ? in n.tags

分解就是:

<select id="selectTestForEach" parameterType="News" resultMap="NewsResultMapper">
  select * from t_news n where 
  <foreach collection="listTag" index="index" item="tag" open=""
    separator="or" close="">
            #{tag} in n.tags
  </foreach>
 </select>


4.

   语句:select * from t_news n where n.tags like ? or n.tags like ?  

  分解是:

       <select id="selectTestForEach" parameterType="News" resultMap="NewsResultMapper">
  select * from t_news n where 
  <foreach collection="listTag" index="index" item="tag" open=""
      separator="or" close="">
             n.tags like  '%'||#{tag}||'%'
  </foreach>
 <select>






0 0
原创粉丝点击