草庐IT

八、动态SQL

钟楼小奶糕6 2023-08-02 原文

一、动态SQL

  • MyBatis框架动态SQL技术是根据特定的条件拼接SQL语句的功能,存在的意义是为了解决拼接SQL语句字符串痛点问题

1.if标签

  • If标签可通过test属性(传递过来的数据)的表达式进行判断。 如果为true标签执行。
  • 在where 后面添加1=1横成立条件

  如果不加这个条件,此刻empName为空的时候,SQL拼接出错select * from t_emp where and age = ? and sex = ? and email = ? 因为where和and连用 

①DynamicSQLMapper接口

/**
 * 多条件查询
 */
List<Emp> getEmp(Emp emp);

②DynamicSQLMapper映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.mybatis.mapper.DynamicSQLMapper">
    <select id="getEmp" resultType="Emp">
        select * from t_emp where 1=1
        <if test="empName != null and empName!=''">
            and emp_name = #{empName}
        </if>
        <if test="age != null and age!=''">
            and age = #{age}
        </if>
        <if test="sex != null and sex!=''">
            and sex = #{sex}
        </if>
        <if test="email != null and email!=''">
            and email = #{email}
        </if>
    </select>
</mapper>

③测试

@Test
public void t1() {
   SqlSession sqlSession = SqlSessionUtils.getSqlSession();
   DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
   Emp emp = new Emp();
   emp.setEmpName("wang");
   List<Emp> emp1 = mapper.getEmp(emp);
   System.out.println(emp1);
}

2.where标签

  • where和if结合
  • 如果所有if标签都不满足,不会在SQL语句拼接where关键字

    如果有if标签满足。会自动添加where关键字,并把条件前面多余的and/or去掉

  • <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.atguigu.mybatis.mapper.DynamicSQLMapper">
        <select id="getEmp" resultType="Emp">
            select * from t_emp
            <where>
                <if test="empName != null and empName!=''">
                    and emp_name = #{empName}
                </if>
                <if test="age != null and age!=''">
                    and age = #{age}
                </if>
                <if test="sex != null and sex!=''">
                    and sex = #{sex}
                </if>
                <if test="email != null and email!=''">
                    and email = #{email}
                </if>
            </where>
    
        </select>
    </mapper>
    

    3.trim

  • trim用于去掉或添加标签中的内容
  • 常用属性
  • prefix:trim标签内容的前面添加某些内容

    suffix:在trim标签内容后面添加某些内容

    prefixOverrides:在trim标签内容前面去掉某些内容

    suffixOverrides:在trim标签内容后面去掉某些内容

  • 若trim中的标签都不满足条件,则trim标签没有任何效果,也就是只剩下select * from t_emp

<trim prefix="where" suffixOverrides="and|or"> 在trim前面加上where,去掉最后面的and

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.mybatis.mapper.DynamicSQLMapper">
    <select id="getEmp" resultType="Emp">
        select * from t_emp
        <trim prefix="where" suffixOverrides="and|or">
            <if test="empName != null and empName!=''">
                 emp_name = #{empName} and
            </if>
            <if test="age != null and age!=''">
                 age = #{age} and
            </if>
            <if test="sex != null and sex!=''">
                 sex = #{sex} and
            </if>
            <if test="email != null and email!=''">
                 email = #{email} and
            </if>
        </trim>

    </select>
</mapper>

4.choose、when、otherwise

  • choose、when、otherwise相当于if…else if…else
  • when至少一个,otherwise至多一个
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.mybatis.mapper.DynamicSQLMapper">
    <select id="getEmp" resultType="Emp">
        select * from t_emp
        <where>
            <choose>
                <when test="empName != null and empName!=''">
                    emp_name = #{empName}
                </when>
                <when test="age != null and age!=''">
                    age = #{age}
                </when>
                <when test="sex != null and sex!=''">
                    sex = #{sex}
                </when>
                <when test="email != null and email!=''">
                    email = #{email}
                </when>
                <otherwise>
                    did = 1
                </otherwise>
            </choose>

        </where>

    </select>
</mapper>

只要when有一个条件成立,when后面的都不执行。When条件都不成立,执行otherwise

5.foreach

  • 属性
  • collection:设置要循环的数组或集合

    item:表示集合或数组的每一个数据

    separator:设置循环之间的分隔符,分隔符前后默认有一个空格

    open:设置foreach标签内容开始符

    close:设置foreach标签内容的结束符

  1. 批量删除
  • 通过数组实现批量删除
  • 除了实体类和Map集合之外,其他参数方式手动加上@Param("xxx")

在DynamicSQLMapper接口里

/**
 * 通过数组实现批量删除
 * 除了实体类对象和Map集合,参数其他方式手动加上@Param("eids")
 */
int deleteByArray(@Param("eids") Integer[] eids);

在DynamicSQLMapper映射文件里

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.mybatis.mapper.DynamicSQLMapper">

    <delete id="deleteByArray">
        delete from t_emp where eid in
        <foreach collection="eids" item="eid" separator="," open="(" close=")">
            #{eid}
        </foreach>
    </delete>
</mapper>

测试

@Test
public void t1() {
   SqlSession sqlSession = SqlSessionUtils.getSqlSession();
   DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
   int deleteCount = mapper.deleteByArray(new Integer[]{5, 6});
   System.out.println("删除成功:"+deleteCount+"条");
}

2.批量删除 

①在DynamicSQLMapper接口

/**
 * 通过List实现批量添加
 */
int insertByList(@Param("emps") List<Emp> emps);

②在DynamicSQLMapper映射文件

实体类对象可以通过#{属性名}得到属性值,如果传过来的是List,#{item.属性名}

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.mybatis.mapper.DynamicSQLMapper">
    <insert id="insertByList">
        insert into t_emp values
        <foreach collection="emps" item="emp" separator=",">
            (null,#{emp.empName},#{emp.age},#{emp.sex},#{emp.email},null)
        </foreach>
    </insert>

</mapper>

 ③测试

   @Test
   public void t1() {
      SqlSession sqlSession = SqlSessionUtils.getSqlSession();
      DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
      Emp emp1 = new Emp(null,"a",1,"男","123@321.com");
      Emp emp2 = new Emp(null,"b",1,"男","123@321.com");
      Emp emp3 = new Emp(null,"c",1,"男","123@321.com");
      List<Emp> emps = Arrays.asList(emp1,emp2,emp3);
      int i = mapper.insertByList(emps);
      System.out.println("成功添加:"+i+"条");
   }

二、SQL片段 

      <sql id="empColumns">eid,emp_name,age,sex,email</sql>

  • sql片段,可以记录一段公共的sql片段,在使用的地方通过include标签进行引入
  • 声明sql片段:<sql>标签
  • 引用sql片段:<include>标签  <include refid="empColumns"></include>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.mybatis.mapper.DynamicSQLMapper">
    <sql id="empColumns">eid,emp_name,age,sex,email</sql>
    <select id="getEmp" resultType="Emp">
        select <include refid="empColumns"></include>from t_emp
        <where>
            <if test="empName != null and empName!=''">
                and emp_name = #{empName}
            </if>
            <if test="age != null and age!=''">
                and age = #{age}
            </if>
            <if test="sex != null and sex!=''">
                and sex = #{sex}
            </if>
            <if test="email != null and email!=''">
                and email = #{email}
            </if>
        </where>

    </select>
</mapper>

 

有关八、动态SQL的更多相关文章

  1. Hive SQL 五大经典面试题 - 2

    目录第1题连续问题分析:解法:第2题分组问题分析:解法:第3题间隔连续问题分析:解法:第4题打折日期交叉问题分析:解法:第5题同时在线问题分析:解法:第1题连续问题如下数据为蚂蚁森林中用户领取的减少碳排放量iddtlowcarbon10012021-12-1212310022021-12-124510012021-12-134310012021-12-134510012021-12-132310022021-12-144510012021-12-1423010022021-12-154510012021-12-1523.......找出连续3天及以上减少碳排放量在100以上的用户分析:遇到这类

  2. sql - 查询忽略时间戳日期的时间范围 - 2

    我正在尝试查询我的Rails数据库(Postgres)中的购买表,我想查询时间范围。例如,我想知道在所有日期的下午2点到3点之间进行了多少次购买。此表中有一个created_at列,但我不知道如何在不搜索特定日期的情况下完成此操作。我试过:Purchases.where("created_atBETWEEN?and?",Time.now-1.hour,Time.now)但这最终只会搜索今天与那些时间的日期。 最佳答案 您需要使用PostgreSQL'sdate_part/extractfunction从created_at中提取小时

  3. ruby - 在 Ruby 中动态创建数组 - 2

    有没有办法在Ruby中动态创建数组?例如,假设我想遍历用户输入的书籍数组:books=gets.chomp用户输入:"TheGreatGatsby,CrimeandPunishment,Dracula,Fahrenheit451,PrideandPrejudice,SenseandSensibility,Slaughterhouse-Five,TheAdventuresofHuckleberryFinn"我把它变成一个数组:books_array=books.split(",")现在,对于用户输入的每一本书,我想用Ruby创建一个数组。伪代码来做到这一点:x=0books_array.

  4. ruby - 是否可以将 IRB 提示配置为动态更改? - 2

    我想在IRB中浏览文件系统并让提示更改以反射(reflect)当前工作目录,但我不知道如何在每个命令后进行提示更新。最终,我想在日常工作中更多地使用IRB,让bash溜走。我在我的.irbrc中试过这个:require'fileutils'includeFileUtilsIRB.conf[:PROMPT][:CUSTOM]={:PROMPT_N=>"\e[1m:\e[m",:PROMPT_I=>"\e[1m#{pwd}>\e[m",:PROMPT_S=>"FOO",:PROMPT_C=>"\e[1m#{pwd}>\e[m",:RETURN=>""}IRB.conf[:PROMPT_MO

  5. ruby-on-rails - carrierwave:在序列化动态属性上安装 uploader - 2

    首先,我使用的是rails3.1.3和来自master的carrierwavegithub仓库的分支。我使用after_init钩子(Hook)来确定基于属性的字段页面模型实例并为这些字段定义属性访问器将值存储在序列化哈希中(希望它清楚我是什么谈论)。这是我正在做的事情的精简版:classPage省略mount_uploader命令让我可以访问我想要的属性。但是当我安装uploader时出现错误消息说“nil类的未定义新方法”我在源代码中读到有方法read_uploader和扩展模块中的write_uploader。我如何必须覆盖这些来制作mount_uploader命令使用我的“虚拟

  6. sql - 在 Rails Console for PostgreSQL 的表中显示数据 - 2

    我找到了这样的东西:Rails:Howtolistdatabasetables/objectsusingtheRailsconsole?这一行没问题:ActiveRecord::Base.connection.tables并返回所有表但是ActiveRecord::Base.connection.table_structure("users")产生错误:ActiveRecord::Base.connection.table_structure("projects")我认为table_structure不是Postgres方法。如何列出Postgres数据库的Rails控制台中表中的所有

  7. ruby - 在 Ruby 中动态生成多维数组 - 2

    我正在尝试动态构建一个多维数组。我想要的基本上是这样的(为简单起见写出来):b=0test=[[]]test[b]这给了我错误:NoMethodError:undefinedmethod`test=[[],[],[]]而且它工作正常,但在我的实际使用中,我不会事先知道需要多少个数组。有一个更好的方法吗?谢谢 最佳答案 不需要像您正在使用的索引变量。只需将每个数组附加到您的test数组:irb>test=[]=>[]irb>test[["a","b","c"]]irb>test[["a","b","c"],["d","e","f"]]

  8. ruby-on-rails - 使用 gmaps4rails 动态加载谷歌地图标记 - 2

    如何只加载map边界内的标记gmaps4rails?当然,在平移和/或缩放后加载新的。与此直接相关的是,如何获取map的当前边界和缩放级别? 最佳答案 我是这样做的,我只在用户完成平移或缩放后替换标记,如果您需要不同的行为,请使用不同的事件监听器:在你看来(index.html.erb):{"zoom"=>15,"auto_adjust"=>false,"detect_location"=>true,"center_on_user"=>true}},false,true)%>在View的底部添加:functiongmaps4rail

  9. ruby - 动态方法链? - 2

    如何在对象上调用方法名称的嵌套哈希?例如,给定以下哈希:hash={:a=>{:b=>{:c=>:d}}}我想创建一个方法,给定上面的散列,执行以下操作:object.send(:a).send(:b).send(:c).send(:d)我的想法是我需要从一个未知的关联中获取一个特定的属性(这个方法不知道,但程序员知道)。我希望能够指定一个方法链来以嵌套哈希的形式检索该属性。例如:hash={:manufacturer=>{:addresses=>{:first=>:postal_code}}}car.execute_method_hash(hash)=>90210

  10. ruby - 防止SQL注入(inject)/好的Ruby方法 - 2

    Ruby中防止SQL注入(inject)的好方法是什么? 最佳答案 直接使用ruby?使用准备好的语句:require'mysql'db=Mysql.new('localhost','user','password','database')statement=db.prepare"SELECT*FROMtableWHEREfield=?"statement.execute'value'statement.fetchstatement.close 关于ruby-防止SQL注入(inject

随机推荐