MyBatis动态SQL之foreach用法

首先简单说下foreach六个属性

item  每一次迭代结果     collection  循环集合成指定类型    separator 元素之间的分隔符,可选

open 开始符号,可选       close 关闭符号,可选       index   list和数组的序号,可选

接着来看一下循环查询的例子

在user.xml中加入

<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 ( ? , ? , ? ) 


//循环赋值

在user.xml中加入

<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>

在测试代码中加入

//动态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开始自动递增的赋值。

猜你喜欢

转载自blog.csdn.net/shixiansen6535/article/details/80525131
今日推荐