if标签
加入我们使用这段sql
语句,SELECT id, username, birthday, sex, address FROM user WHERE sex = #{sex} AND username LIKE '%${username}%'
,通过性别和姓名查询信息,但是突然需求被改成只通过username
查询信息,那么我们还需要再写一条查询语句,这样重复性劳动太多,其实我们可以把第二种情况下传入sex
的参数设置为null
,然后使用if
标签来判断一下,如果传入的sex
不空,就把这个条件加上,否则不加。
<select id="twoParams" resultType="User">
select user_id as id username, birthday, sex, address from user where
<!-- 字符串类型需要判断不为空,不为'',其他类型只需要判断不为空 -->
<if test="date != null">
birthday = #{date} and
</if>
address = #{address}
</select>
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> users = userDao.twoParams(null, "aaaaaa");
System.out.println(users);
where标签
在上面的语句中配置if
标签后,一条语句能被使用两次,但是如果我们还想拓展到把addresss
也可以动态加入就会产生问题。这个问题是and
产生的,因为如果把and放在date的后面,如果address
为空,最后形成的语句是: ... where date = #{date} and
,如果放在address
的前面,date
为空时,最后形成的语句是:... and address = #{address}
。而where
标签的作用就是去掉and,但是它只能去掉第一个前and
。
<select id="twoParams" resultType="User">
select user_id as id, username, birthday, sex, address from user
<!-- 字符串类型需要判断不为空,不为'',其他类型只需要判断不为空 -->
<where>
<if test="date != null">
birthday = #{date}
</if>
<if test="address != null and address != ''">
and address = #{address}
</if>
</where>
</select>
for…each
像下面的代码:SELECT * FROM user WHERE id IN (1,10,24)
,我们想向里面注入一个集合,需要使用for..each
。(数组也一样)
<select id="moreIds" resultType="User">
select user_id as id, username, birthday, sex, address from user where user_id in
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</select>
public List<User> moreIds(@Param("ids")List<Integer> ids);