MyBatis動態SQL(二)

1.foreach

foreach語句用來遍歷數組和集合對象。標籤中的屬性:
collection屬性:值有三種list、array、map
open屬性:表示調用的sql語句前綴添加的內容
close屬性:表示調用的sql語句後綴添加的內容
separator屬性:分隔符,表示每一次迭代元素之間用什麼分隔
item屬性:表示迭代時,每個元素的別名
index屬性:表示當前循環的索引位置
映射文件配置代碼:

<select id="queryByList" parameterType="list" resultMap="baseMap">
		select * from t_user where no in
		<foreach collection="nos" open="(" close=")" separator="," item="no">
			#{no}
		</foreach>
	</select>

方法的接口代碼:

//list,map參數必須添加註解@param不然配置文件會找不着參數而報錯
public List<User> queryByList(@Param("nos")List<Integer> nos);

測試代碼:

public class TestSQL {
	public static IUserDao mapper = IUserMapper.getIUserMapper();
	public static void main(String[] args) {
		List<Integer> list = new ArrayList<Integer>();
		list.add(1009);
		list.add(1111);
		List<User> user = mapper.queryByList(list);
		for (User user2 : user) {
			System.out.println(user2);
		}
	}
}

測試結果:
在這裏插入圖片描述

2.bind

bind元素就是在OGNL表達式中創建一個變量,然後在整個表達式範圍內都可以使用。
映射文件配置代碼:

<select id="queryById" resultType="user" parameterType="int">
		<bind name="abc" value="1009"/>
		select * 
		from t_user 
		<where>
			<if test="no=null" >
					 no=${abc}
				</if>
		</where>
	</select>

測試結果:
在這裏插入圖片描述

3.sql塊

sql片段一般用來定義sql中的列屬性。如下例子:
映射文件配置代碼:

<!-- 定義好sql片段 -->
	<sql id="sql">
		no,name,age
	</sql>
	<select id="queryByList" parameterType="list" resultMap="baseMap">
		select 
		<!-- 引用定義好的sql片段 -->
		<include refid="sql"></include> 
		from t_user where no in
		<foreach collection="nos" open="(" close=")" separator="," item="no">
			#{no}
		</foreach>
	</select>
	
	<insert id="add" parameterType="user">
		insert into t_user(
		<!-- 引用定義好的sql片段 -->
		<include refid="sql"></include>
		) values(#{no},#{name},#{age}) 
	</insert>

測試結果:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章