动态SQL常用控制语句
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
1、if语句使用
可以使用if进行动态模糊查询,我们修改原有的模糊查询映射代码
<!--模糊查询-->
<select id="findByName" parameterType="user" resultMap="userMap">
select * from user where 1=1
<if test="userName != null and userName != ''">
and username like #{userName}
</if>
<if test="userAddress != null">
and address like #{userAddress}
</if>
</select>
测试代码如下:
/**
* 模糊动态查询
*/
@Test
public void testFindByName(){
User u = new User();
u.setUserName("%王%");
u.setUserAddress("%成都%");
List<User> users = userDao.findByName(u);
for (User user:users){
System.out.println(user);
}
}
2、where标签使用
上面我们未使用where标签所以使用1=1作为条件,使用where标签后调整如下
<!--模糊查询-->
<select id="findByName" parameterType="user" resultMap="userMap">
select * from user
<where>
<if test="userName != null and userName != ''">
and username like #{userName}
</if>
<if test="userAddress != null">
and address like #{userAddress}
</if>
</where>
</select>
3、foreach标签使用
我们新增一个UserDao接口中新增findByIds方法
配置我们的映射文件如下:
<!--动态查询-多id查询-->
<select id="findByIds" parameterType="com.shenqiang.domain.QueryVo" resultMap="userMap">
select * from user
<where>
<if test="ids != null and ids.size()>0">
<foreach collection="ids" item="uid" open="id in (" separator="," close=")">
#{uid}
</foreach>
</if>
</where>
</select>
这个使用foreach时相当于使用了拼接我们将我们的查询语句拼接进去。
collection:代表要遍历的集合元素,注意编写时不要写#{}
open:代表语句的开始部分
close:代表结束部分
item:代表遍历集合的每个元素,生成的变量名
sperator:代表分隔符