mybaties中where in條件寫法,獲取某對象List的一個屬性


MyBatis中提供了foreach語句實現IN查詢,foreach語法如下:

foreach語句中, collection屬性的參數類型可以使:List、數組、map集合
​ collection: 必須跟mapper.java中@Param標簽指定的元素名一樣
​ item: 表示在迭代過程中每一個元素的別名,可以隨便起名,但是必須跟元素中的#{}里面的名稱一樣。
   index:表示在迭代過程中每次迭代到的位置(下標)
   open:前綴, sql語句中集合都必須用小括號()括起來
​ close:后綴
   separator:分隔符,表示迭代時每個元素之間以什么分隔

正確的寫法有以下幾種寫法:

 

(一)、selectByIdSet(List idList)

 

如果參數的類型是List, 則在使用時,collection屬性要必須指定為 list

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

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

 

如果參數的類型是Array,則在使用時,collection屬性要必須指定為 array

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

(三)、參數有多個時

 

當查詢的參數有多個時,有兩種方式可以實現,一種是使用@Param("xxx")進行參數綁定,另一種可以通過Map來傳參數。

 

3.1 @Param("xxx")方式

List<User> selectByIdSet(@Param("name")String name, @Param("ids")String[] idList);
 
<select id="selectByIdSet" resultMap="BaseResultMap">
    SELECT
    <include refid="Base_Column_List" />
    from t_user
    WHERE  name=#{name,jdbcType=VARCHAR} and id IN
    <foreach collection="idList" item="id" index="index"
             open="(" close=")" separator=",">
      #{id}
    </foreach>
</select>

3.2 Map方式

Map<String, Object> params = new HashMap<String, Object>(2);
params.put("name", name);
params.put("idList", ids);
mapper.selectByIdSet(params);
 
<select id="selectByIdSet" resultMap="BaseResultMap">  
     select  
     <include refid="Base_Column_List" />  
     from t_user where 
     name = #{name}
     and ID in  
     <foreach item="item" index="index" collection="idList" open="(" separator="," close=")">  
      #{item}  
     </foreach>  
</select>

---------------------------------------------------------------------------------------------------------

獲取list對象一個屬性,例如獲取list對象GoodsResp01的屬性comUid的set或者list

List<GoodsResp01> list = goodsService.selectGoodsInfoList(comName);

Set<Integer> collect = list.stream().map(GoodsResp01::getComUid).collect(Collectors.toSet());//去重

List<Integer> collectlist = list.stream().map(GoodsResp01::getComUid).collect(Collectors.toList());


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



猜您在找 Java中怎樣根據對象list的某對象的屬性進行分組 高效地根據屬性名獲取某對象的屬性值 C# List按某對象的屬性分組 IGrouping 獲取List中對象的屬性值 從List獲取集合中對象的某個屬性 java 從List中獲取一個對象 java8 list轉map,list集合中的元素的屬性轉set,list集合中對象的屬性轉list,list 排序,list分組,條件過濾 獲取List集合對象中某一列屬性值 C#,關於從List或Collection中找出對象的某個屬性值與另一個list相同的全部對象 獲取List 中Map的屬性值列表,獲取所有map對象的某個屬性列表
 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM