在说动态SQL之前,先说说我们之前使用用什么执行SQL语句呢?答案就是JDBC。回想之前在使用传统JDBC的时候,在操作复杂的SQL语句的时候,我们如果没有仔细的话,那么就会导致出错,比如SQL语句结束的时候可能多加了一个或者空格。因此,Mybatis提供一种功能:MySQL动态查询,其中涉及的标签有如下: if, choose, when, otherwise, trim, where, set, foreach标签。利用这些标签可以解决这些很烦的问题。下面我一一来介绍吧。
一:if标签 (简单条件判断)
<select id="findUserById" parameterType="UserPo.User" resultType="UserPo.User"> select * from user WHERE <if test="sex!=null"> sex=#{sex} </if> <if test="id!=null"> and id=#{id} </if> </select>
解析:
看见WhERE后面有一个标签if了么?如果我们没有满足test这里面的条件,比如sex!=null和id!=null,那么才能拼接成 select * from user where sex = ? and id =? 之后根据对应的参数,若满足这些条件就返回所有结果。
以往我们需要jdbc连接的话,String sql = "select * from t_user where sext='"+ sex +"' and id='"+ id +"'",写起来发现麻烦。比起来,动态SQL要简单多了
不过这个if标签也有点问题,如果sex刚好等于null呢?那么这条语句就出问题了,就会变成 select * from user WHERE and id = ?; 那么下面,where可以解决这个问题
二:where标签(常用,拼接条件的时候经常使用)
继续使用上面那个例子,只是在外面加了一个where标签
<select id="findUserById" parameterType="UserPo.User" resultType="UserPo.User"> select * from user <where> <if test="sex!=null"> and sex=#{sex} </if> <if test="id!=null"> and id=#{id} </if> </where> </select>
where呢 除了我们拼接条件的时候经常使用外,就是有个很好使用的功能:当使用where标签的时候,可以灵活处理 AND / OR 的问题,当然,有时候如果不可以的话,那么可以实现trim
三: trim标签(修改或者去除)
<select id="findUserById" parameterType="UserPo.User" resultType="UserPo.User"> select * from user <where> <if test="address!=null"> address = #{value} </if> <trim prefix="where" prefixOverrides="and| or "> <if test="sex!=null"> and sex=#{sex} </if> </trim> <if test="id!=null"> and id=#{id} </if> </where> </select>
这个trim里面标签最终意思:WHERE后紧随AND或则OR的时候,就去除AND或者OR。 除了WHERE以外。
四: set 标签(类似where)
<update id="updateUser" parameterType="UserPo.User"> update user <set> <if test="username!=null"> #{username}, </if> <if test="sex!=null"> #{User.sex}, </if> <if test="id!=null"> #{id} </if> </set> where id=#{id} </update>
当你的test==null时那sql语句不就变成: update user set #{username}, #{User.sex}, where id=#{id} ; 看见了吗 多了一个, 这样岂不是会SQL语句出错啦,这时set可以去除不必要的逗号。
其实这里也可以用前面的trim操作,使用 <trim prefix="SET" suffixOverrides=","></trim>
五:choose (类似当时学Java中的switch)
<select id="findUserById" parameterType="UserPo.User" resultType="UserPo.User"> select * from user where 1=1 <choose> <when test="username!=null"> and username like #{username} </when> <when test="sex!=null"> and sex = {sex} </when> <otherwise> and 1=1 </otherwise> </choose> </select>
解析: choose字母意思是选择的意思,当username和sex二者都不是null的时候,那么我们该选择那个呢?选择最先满足的,依据这个查询的话,那么就是执行username这个。
若二者都为null呢,那么执行otherwise。 反正这个东西类似Java中的switch