动态SQL
1 为什么学习动态SQL
- 动态SQL可以满足实际开发中
多条件
查询功能。
2 什么是动态SQL
- 动态SQL:根据数据的不同,动态的拼凑SQL语句技术。
- 拼凑技术:
- 判断 if
- 循环forEach
- 简化条件 where
3 判断 if
-
场景1:通过id查询用户详情,如果id不存在查询所有。
-
功能接口的功能方法
List<User> selectBySQL(String uid);
-
xml配置
<!-- 通过id查询详情 --> <select id="selectBySQL" parameterType="string" resultType="com.czxy.ssm.domain.User"> select * from user <if test="uid != null and uid != ''"> where uid =#{uid} </if> </select>
-
-
场景2:通过用户名和密码查询用户详情,如果用户名和密码不存在查询所有。
-
功能接口的功能方法
public List<User> selectBySQL2(@Param("username") String username,@Param("password") String password);
-
xml配置
<!-- 动态SQL,2个条件 ,提供恒等条件 where 1=1 --> <select id="selectBySQL2" resultType="com.czxy.ssm.domain.User"> select * from user where 1=1 <if test="username != null and username != ''"> and user_name = #{username} </if> <if test="password != null and password != ''"> and password = #{password} </if> </select>
-
4 简化条件 where
<select id="selectBySQL2" resultType="com.czxy.ssm.domain.User">
select * from user
<where>
<if test="username != null and username != ''">
and user_name = #{username}
</if>
<if test="password != null and password != ''">
and password = #{password}
</if>
</where>
</select>
5 循环forEach
-
目标:使用forEach拼凑SQL片段
uid in (1,2,3)
-
步骤:
- 编写条件查询封装对象:UserVo. ids 集合
- 编写功能接口:condition
- 编写XML,拼凑条件
-
实现:
-
编写条件查询封装对象:UserVo. ids 集合
package com.czxy.ssm.vo; import java.util.ArrayList; import java.util.List; public class UserVo { private List<String> ids = new ArrayList<>(); public List<String> getIds() { return ids; } public void setIds(List<String> ids) { this.ids = ids; } }
-
编写功能接口:condition
/** * 多条件查询 * @param userVo * @return */ public List<User> condition(UserVo userVo);
-
编写XML,拼凑条件
<!-- select * from user where uid in ('u001','u002','u003') --> <select id="condition" resultType="com.czxy.ssm.domain.User"> select * from user <where> <foreach collection="ids" open="uid in (" item="id" separator="," close=")"> '${id}' </foreach> </where> </select>
- 注意事项:
- 使用forEach拼凑,如果是字符类型,需要使用引号。
6 if + forEach
- 通过size可以判断list计划的元素数量
<!-- select * from user where uid in ('u001','u002','u003') -->
<select id="condition" resultType="com.czxy.ssm.domain.User">
select * from user
<where>
<if test="ids != null and ids.size > 0">
<foreach collection="ids" open="uid in (" item="id" separator="," close=")">
'${id}'
</foreach>
</if>
</where>
</select>