1. 程式人生 > 程式設計 >Mybatis動態SQL foreach標籤用法例項

Mybatis動態SQL foreach標籤用法例項

需求:傳入多個 id 查詢使用者資訊,用下邊兩個 sql 實現:

SELECT * FROM USERS WHERE username LIKE '%張%' AND (id =10 OR id =89 OR id=16)

SELECT * FROM USERS WHERE username LIKE '%張%' AND id IN (10,89,16)

這樣我們在進行範圍查詢時,就要將一個集合中的值,作為引數動態新增進來。

這樣我們將如何進行引數的傳遞?

1、實體類

public class QueryVo implements Serializable {
  private List<Integer> ids;
  
	public List<Integer> getIds() {
		return ids; 
  }
  
	public void setIds(List<Integer> ids) {
		this.ids = ids; 
  } 
}

2、持久層介面

/**
* 根據 id 集合查詢使用者
* @param vo
* @return
*/
List<User> findInIds(QueryVo vo);

3、對映檔案

<!-- 查詢所有使用者在 id 的集合之中 -->
<select id="findInIds" resultType="user" parameterType="queryvo">
  <!-- select * from user where id in (1,2,3,4,5); -->
	select * from user 
  <where> 
    <if test="ids != null and ids.size() > 0"> 
      <foreach collection="ids" open="id in ( " close=")" item="uid" separator=",">
		#{uid}
	  </foreach>
	</if>
  </where>
</select>

SQL 語句:

select 欄位 from user where id in (?)

foreach標籤用於遍歷集合,它的屬性

  • collection:代表要遍歷的集合元素,注意編寫時不要寫#{}
  • open:代表語句的開始部分
  • close:代表結束部分
  • item:代表遍歷集合的每個元素,生成的變數名
  • sperator:代表分隔符

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。