Mybatis05_动态的SQL语句
1、动态SQL值<if>标签
根据业务的实际需求不同,有时需要不同的SQL语句。比如设置过滤条件,根据名字、id过滤。
如果id不为空就根据id过滤,如果名字不为空就根据名字过滤,如果两者都不为空则都作为过滤条件。这种情况就需要我们通过if判断
<select id="findByUser" resultType="user" parameterType="user"> select * from user where 1=1 <if test="username!=null and username != '' "> and username like #{username} </if> <if test="address != null"> and address like #{address} </if> </select> 注意:<if>标签的 test 属性中写的是对象的属性名,如果是包装类的对象要使用 OGNL 表达式的写法。注意没有else的匹配使用 另外要注意 where 1=1 的作用~!
2、动态SQL之<where>标签
比如用来替换上面的where 1=1
<!-- 根据用户信息查询 --> <select id="findByUser" resultType="user" parameterType="user"> <include refid="defaultSql"></include> <where> <if test="username!=null and username != '' "> and username like #{username} </if> <if test="address != null"> and address like #{address} </if> </where> </select>
3、动态SQL之<foreach>标签
情景:传入多个id来查询用户的SQL语句为
SELECT * FROM USERS WHERE username LIKE '%张%' AND (id =10 OR id =89 OR id=16)
SELECT * FROM USERS WHERE username LIKE '%张%' AND id IN (10,89,16)
这样我们查询的时候就需要将一个集合中的值,作为动态参数传递进来
public class QueryVo implements Serializable { private List<Integer> ids; public List<Integer> getIds() { return ids; } public void setIds(List<Integer> ids) { this.ids = ids; } } <!-- 查询所有用户在 id 的集合之中 --> <select id="findInIds" resultType="user" parameterType="queryvo"> <include refid="defaultSql"></include> <where> <if test="ids != null and ids.size() > 0"> <foreach collection="ids" open="id in ( " close=")" item="uid" separator=","> #{uid} </foreach> </if> </where> </select>
SQL 语句: select 字段 from user where id in (?) <foreach>标签用于遍历集合,它的属性: collection:代表要遍历的集合元素,注意编写时不要写#{} open:代表语句的开始部分 close:代表结束部分
item:代表遍历集合的每个元素,生成的变量名
sperator:代表分隔符
4、扩展
1)SQL片段:可以将重复的SQL提取出来,使用的时候通过include引入即可,达到SQL重用
<sql id="defaultSql"> select * from user </sql> <select id="findAll" resultType="user"> <include refid="defaultSql"></include> </select>

浙公网安备 33010602011771号