当前位置:Gxlcms > 数据库问题 > Mybatis 动态SQL

Mybatis 动态SQL

时间:2021-07-01 10:21:17 帮助过:19人阅读

  以 User 表为例来说明: 技术图片技术图片   1、if 语句          根据 username 和 sex 来查询数据。如果username为空,那么将只根据sex来查询;反之只根据username来查询          首先不使用 动态SQL 来书写      <select id="selectUserByUsernameAndSex" resultType="user" parameterType="com.ys.po.User">         <!-- 这里和普通的sql 查询语句差不多,对于只有一个参数,后面的 #{id}表示占位符,里面不一定要写id,             写啥都可以,但是不要空着,如果有多个参数则必须写pojo类里面的属性 -->         select * from user where username=#{username} and sex=#{sex}       </select>    上面的查询语句,我们可以发现,如果 #{username} 为空,那么查询结果也是空,如何解决这个问题呢?使用 if 来判断           <select id="selectUserByUsernameAndSex" resultType="user" parameterType="com.ys.po.User">      select * from user where         <if test="username != null">            username=#{username}         </if>                   <if test="sex != null">            and sex=#{sex}         </if>     </select>        这样写我们可以看到,如果 sex 等于 null,那么查询语句为 select * from user where username=#{username},但是如果usename 为空呢?那么查询语句为 select * from user where and sex=#{sex},这是错误的 SQL 语句,如何解决呢?请看下面的 where 语句     2、if + where 语句    <select id="selectUserByUsernameAndSex" resultType="user" parameterType="com.ys.po.User">       select * from user        <where>         <if test="username != null">            username=#{username}         </if>                   <if test="sex != null">            and sex=#{sex}         </if>     </where>    </select>      这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以AND 或OR 开头的,则它会 剔除掉。    3、if + set 语句    同理,上面的对于查询 SQL 语句包含 where 关键字,如果在进行更新操作的时候,含有 set 关键词,怎么处理呢    <!-- 根据 id 更新 user 表的数据 -->     <update id="updateUserById" parameterType="com.ys.po.User">         update user u         <set>             <if test="username != null and username != ‘‘">                 u.username = #{username},             </if>             <if test="sex != null and sex != ‘‘">                 u.sex = #{sex}             </if>         </set>            where id=#{id}    </update>     

人气教程排行