Mybatis動態Sql的Foreach遍歷拼接輸入引數中的List或陣列

劉蒞發表於2016-12-23

pojo、pojo包裝類

public class User {
	private int id;
	private String username;
	private String sex;
	private Date birthday;
	private String address;
	//省略get/set方法
}


//繼承User類
public class UserCustom extends User {

}

/*
包裝類
 * */
public class UserQueryVo {
	private UserCustom userCustom;
	private List<Integer> ids;	//從pojo類中讀取List
}

當paramterType是UserQueryVo時,需要取出ids的值,用foreach遍歷

UserMapper.xml

<sql id="findUser_where">
		<if test="userCustom">
			<if test="userCustom.sex != null and userCustom.sex != ''">
				and sex = #{userCustom.sex}
			</if>
			<!--  
				使用foreach遍歷傳入的ids集合
				collection:指定輸入的物件中集合的屬性
				item:每次遍歷的元素生成的物件
				open:開始遍歷時生成的串
				close:結束遍歷時生成的串
				separator:遍歷的兩個物件中需要生成的串
			 -->
			<if test="ids != null">
                 <!--最終生成的SQL語句: select * from user where sex = '' and (id= or id= or id= ) and username like '' -->
				<foreach collection="ids" item="user_id" open="and (" close=")" separator="or">
				<!-- 每個遍歷需要生成的串 -->
					id=#{user_id}
				</foreach>
			</if>
             <!-- 與上面的foreach等價
			<if test="ids != null">
                  最終生成的SQL語句: select * from user where sex = '' and id in(1,2,3) and username like ''
				<foreach collection="ids" item="user_id" open="and id in(" close=")" separator=",">
					#{user_id}
				</foreach>
			</if>
			
			 -->
			<if test="userCustom.username != null and userCustom.username != ''">
				and username like '%${userCustom.username}%'
			</if>
		</if>
	</sql>
    <select id="findUserByIds" parameterType="cn.itcast.mybatis.po.UserQueryVo" resultType="cn.itcast.mybatis.po.UserCustom">
		select * from user
		<!-- 最好不要將where語句包括進去 -->
		<where>
			<!-- 引用sql片段 ,如果refid指定的id不在本mapper中,需要指定namesapce-->
			<include refid="findUser_where"></include>
		</where>
	</select>




相關文章