1. 程式人生 > >mybatis傳入陣列並且遍歷

mybatis傳入陣列並且遍歷

 <select id="selectByTagIds" resultMap="BaseResultMap" parameterType="java.lang.String" >
    select
    <include refid="Base_Column_List" />
    from hb_information_tags
    where 1=1
    <if test="tagIds!=null">
      and tag_id in 
      <foreach collection="array" item="tagId"
index="index" open="(" close=")" separator=","> '${tagId}' </foreach> </if> </select>

這裡傳入的array是一個數組。通過foreach封裝成一個類似於(1,2,3)的字串。(注意,傳入的陣列必須命名為array)

當傳入的tagIds是一個類似於”1,2,3”的字串時,語句寫成即可:

 and tag_id in
      (${tagIds})

—-20180702補充:
這個部落格寫了好久了,這次又要用到傳陣列的功能,忽然想不起來怎麼寫了,就把這個翻出來參考。發現,在目前使用的版本中,直接傳入逗號分隔字串的方式並不可取。使用傳入陣列方式,陣列並不一定要命名為array,在傳入的實體中,將這個陣列欄位的getter寫好就成。