MyBatis動態SQL之foreach用法

首先簡單說下foreach六個屬性java

item  每一次迭代結果     collection  循環集合成指定類型    separator 元素之間的分隔符,可選數組

open 開始符號,可選       close 關閉符號,可選       index   list和數組的序號,可選session

接着來看一下循環查詢的例子mybatis

在user.xml中加入ide

<select id="selectUserForeach" resultType="User" parameterType="list"> 
	select * from user  
		<where>
			id in
			<foreach item="item" index="index" collection="list"
				open="(" separator="," close=")">
				#{item}
			</foreach>
		</where>
</select>

在測試代碼中加入
測試

ArrayList<Integer> ides=new ArrayList();
			ides.add(2);
			ides.add(8);
			ides.add(9);
			List<User> ap=session.selectList("selectUserForeach", ides);
			for(User temp:ap) {		
			System.out.println("用戶ID="+temp.getId()+"用戶名="+temp.getUserName()
			+"密碼="+temp.getPassword());
			}

運行,控制檯就會打印出id爲2,8,9的相關屬性的值,執行的SQL語句爲select * from user WHERE id in ( ? , ? , ? ) code


//循環賦值xml

在user.xml中加入get

<insert id="insertUserForeach">
		 insert into User (userName, password) values  
      <foreach item="item" index="key" collection="list"  
           open="" separator="," close="">(#{item.userName}, #{item.password})
       </foreach>  	
	</insert>

在測試代碼中加入it

//動態SQL之foreach 循環賦值
			ArrayList<User> jList=new ArrayList();
			User one=new User("kb1","8866");
			User two=new User("kb2","8866");
			jList.add(one);
			jList.add(two);
			session.insert("insertUserForeach",jList);
			session.commit();

運行,執行的SQL語句爲insert into User (userName, password) values (?, ?) , (?, ?) 

若把user.xml中的item.userName改爲key,則mybatis會自動把userName的值從0開始自動遞增的賦值。

以上即是MyBatis中foreach的例子,歡迎指出不足之處,互相交流,謝謝。

相關文章
相關標籤/搜索