• mybatis 动态sql!!!


    技术总结:

    1、动态SQL: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 来判断

    ``

    这样写我们可以看到,如果 sex 等于 null,那么查询语句为 select * from user where username=#{username},但是如果usename 为空呢?那么查询语句为 select * from user where and sex=#{sex},这是错误的 SQL 语句,如何解决呢?请看下面的 where 语句

    2、动态SQL:if+where 语句
    ``

    这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以AND 或OR 开头的,则它会剔除掉。

    3、动态SQL:if+set 语句

    `

    update user u


    u.username = #{username},


    u.sex = #{sex}

     where id=#{id}
    

    `

    这样写,如果第一个条件 username 为空,那么 sql 语句为:update user u set u.sex=? where id=?

          如果第一个条件不为空,那么 sql 语句为:update user u set u.username = ? ,u.sex = ? where id=?

    动态SQL:choose(when,otherwise) 语句
      有时候,我们不想用到所有的查询条件,只想选择其中的一个,查询条件有一个满足即可,使用 choose 标签可以解决此类问题,类似于 Java 的 switch 语句

    <select id="selectUserByChoose" resultType="com.ys.po.User" parameterType="com.ys.po.User"> select * from user <where> <choose> <when test="id !='' and id != null"> id=#{id} </when> <when test="username !='' and username != null"> and username=#{username} </when> <otherwise> and sex=#{sex} </otherwise> </choose> </where> </select>
      也就是说,这里我们有三个条件,id,username,sex,只能选择一个作为查询条件

        如果 id 不为空,那么查询语句为:select * from user where id=?

        如果 id 为空,那么看username 是否为空,如果不为空,那么语句为 select * from user where username=?;

              如果 username 为空,那么查询语句为 select * from user where sex=?

    5、动态SQL:trim 语句
      trim标记是一个格式化的标记,可以完成set或者是where标记的功能

    ①、用 trim 改写上面第二点的 if+where 语句
    `

  • 相关阅读:
    Spring 学习笔记
    Hello Spring(3)ConnectionUtility
    android ndk开发
    java udp 广播及socket通讯
    android 横向滚动屏幕实现(2)
    android 基于ftp远程文件管理
    android 软键盘的弹出问题总结
    android 滚动字幕
    android 基于apache ftp server
    android 设置壁纸几种方法
  • 原文地址:https://www.cnblogs.com/xjyboke/p/13955966.html
Copyright © 2020-2023  润新知