草庐IT

MyBatis--动态SQL

aruba 2023-09-28 原文

接着上篇MyBatis--代理模式实现数据库增删改查,对于某些需要拼接的复杂SQL语句,MyBatis在映射文件中预定义了一些标签,可以利用这些标签来方便拼接自己的逻辑

一、if标签

顾名思义,if标签就是用来实现if判断的

实现根据员工对象获取员工信息,员工对象中的单个属性为空,则不参与查询条件

定义接口方法:

    /**
     * 根据员工对象获取员工信息
     * @param emp
     * @return
     */
    List<Emp> findByEmp(Emp emp);

映射文件新增查询:

    <!--List<Emp> findByEmp(Emp emp);-->
    <select id="findByEmp" resultType="emp">
        select * from emp where 1 = 1
        <if test="empno != null ">
            and empno = #{empno}
        </if>
        <if test="ename != null ">
            and ename = #{ename}
        </if>
        <if test="job != null ">
            and job = #{job}
        </if>
        <if test="mgr != null ">
            and mgr = #{mgr}
        </if>
        <if test="hiredate != null ">
            and hiredate = #{hiredate}
        </if>
        <if test="sal != null ">
            and sal = #{sal}
        </if>
        <if test="comm != null ">
            and comm = #{comm}
        </if>
        <if test="deptno != null ">
            and deptno = #{deptno}
        </if>
    </select>

测试方法:

    // 根据员工信息动态sql查询员工 -- if
    @Test
    public void test1() {
        EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
        Emp emp = new Emp();
        emp.setDeptno(20);
        List<Emp> result = mapper.findByEmp(emp);
        result.forEach(System.out::println);
    }

二、where标签

上面我们在where后面跟了个 1 = 1,原因是不加会形成where and ename = ...这种情况,那么sql语句就出错了,也可以直接使用where标签替代

通过where标签查询员工信息

映射文件使用where标签:

    <!--List<Emp> findByEmp(Emp emp);-->
    <select id="findByEmp" resultType="emp">
        select * from emp
        <where>
            <if test="empno != null ">
                and empno = #{empno}
            </if>
            <if test="ename != null ">
                and ename = #{ename}
            </if>
            <if test="job != null ">
                and job = #{job}
            </if>
            <if test="mgr != null ">
                and mgr = #{mgr}
            </if>
            <if test="hiredate != null ">
                and hiredate = #{hiredate}
            </if>
            <if test="sal != null ">
                and sal = #{sal}
            </if>
            <if test="comm != null ">
                and comm = #{comm}
            </if>
            <if test="deptno != null ">
                and deptno = #{deptno}
            </if>
        </where>
    </select>

三、choose标签

choose标签相当于switch语句,并且只要有一个匹配了,就break不往下执行了
choose标签和when标签配合使用

通过choose标签查询员工信息

映射文件:

    <select id="findByEmp2" resultType="emp">
        select * from emp
        <where>
            <choose>
                <when test="empno != null ">
                    and empno = #{empno}
                </when>
                <when test="ename != null ">
                    and ename = #{ename}
                </when>
                <when test="job != null ">
                    and job = #{job}
                </when>
                <when test="mgr != null ">
                    and mgr = #{mgr}
                </when>
                <when test="hiredate != null ">
                    and hiredate = #{hiredate}
                </when>
                <when test="sal != null ">
                    and sal = #{sal}
                </when>
                <when test="comm != null ">
                    and comm = #{comm}
                </when>
                <when test="deptno != null ">
                    and deptno = #{deptno}
                </when>
            </choose>
        </where>
    </select>

测试方法:

    // 根据员工信息动态sql查询员工 -- choose
    @Test
    public void test2() {
        EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
        Emp emp = new Emp();
        emp.setJob("SALESMAN");
        emp.setDeptno(20);
        List<Emp> result = mapper.findByEmp2(emp);
        result.forEach(System.out::println);
    }

结果打印为职位为SALESMAN条件的员工,部门并不生效

四、set标签

set标签用于数据库更新操作

实现更新员工信息

定义接口方法:

    /**
     * 更新员工信息
     * @param emp
     * @return
     */
    int updateEmp(Emp emp);

映射文件中新增更新:

    <!--int updateEmp(Emp emp);-->
    <update id="updateEmp">
        update emp
        <set>
            <if test="ename != null and ename != '' ">
                ,ename = #{ename}
            </if>
            <if test="job != null and job != '' ">
                ,job = #{job}
            </if>
            <if test="mgr != null ">
                ,mgr = #{mgr}
            </if>
            <if test="hiredate != null ">
                ,hiredate = #{hiredate}
            </if>
            <if test="sal != null ">
                ,sal = #{sal}
            </if>
            <if test="comm != null ">
                ,comm = #{comm}
            </if>
            <if test="deptno != null ">
                ,deptno = #{deptno}
            </if>
        </set>
        where empno = #{empno}
    </update>

其中要注意的是:if标签中要加上","

测试方法:

    // 更新员工信息 -- set
    @Test
    public void test3() {
        EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
        Emp emp = new Emp();
        emp.setEmpno(7499);
        emp.setJob("SALESMAN");
        emp.setDeptno(20);
        int result = mapper.updateEmp(emp);
        System.out.println(result);

        sqlSession.commit();
    }

五、trim标签

set标签相当于在每个if标签中加上"set"前缀,trim标签支持自定义前缀和后缀

set标签实现更新员工信息

映射文件使用trim:

    <update id="updateEmp2">
        update emp
        <trim prefix="set" prefixOverrides=",">
            <if test="ename != null and ename != '' ">
                ,ename = #{ename}
            </if>
            <if test="job != null and job != '' ">
                ,job = #{job}
            </if>
            <if test="mgr != null ">
                ,mgr = #{mgr}
            </if>
            <if test="hiredate != null ">
                ,hiredate = #{hiredate}
            </if>
            <if test="sal != null ">
                ,sal = #{sal}
            </if>
            <if test="comm != null ">
                ,comm = #{comm}
            </if>
            <if test="deptno != null ">
                ,deptno = #{deptno}
            </if>
        </trim>
        where empno = #{empno}
    </update>

prefixOverrides表示除去第一个匹配的前缀,相应的还有suffixOverrides,用于去除第一个匹配的后缀

六、bind标签

bind标签一般用于模糊查询的模板

实现根据姓名模糊查询员工信息

定义接口方法:

    /**
     * 根据姓名模糊查询员工信息
     * @param ename
     * @return
     */
    List<Emp> findByEname(String ename);

映射文件新增查询:

    <!--List<Emp> findByEname(String ename);-->
    <select id="findByEname" resultType="emp">
        <bind name="likeEname" value="'%'+ename+'%'"/>
        select * from emp where ename like #{likeEname}
    </select>

测试方法:

    // 根据姓名模糊查询员工信息 -- bind
    @Test
    public void test5() {
        EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
        List<Emp> result = mapper.findByEname("a");
        result.forEach(System.out::println);
    }

七、sql标签

sql标签就是预定义一些常用的字符串当作变量
sql标签与include标签配合使用

在映射文件中定义包含所有表字段的变量,争对上面的模糊查询进行修改
原:

    <!--List<Emp> findByEname(String ename);-->
    <select id="findByEname" resultType="emp">
        <bind name="likeEname" value="'%'+ename+'%'"/>
        select * from emp where ename like #{likeEname}
    </select>

修改后:

    <sql id="empColumn">empno,ename,job,mgr,hiredate,sal,comm,deptno</sql>
    <sql id="baseSelect">select <include refid="empColumn"/> from emp</sql>

    <!--List<Emp> findByEname(String ename);-->
    <select id="findByEname" resultType="emp">
        <bind name="likeEname" value="'%'+ename+'%'"/>
        <include refid="baseSelect" /> where ename like #{likeEname}
    </select>

八、foreach标签

foreach标签用于将数组或List集合拼接

实现根据部门编号数组查询员工信息

定义接口方法:

    /**
     * 根据部门编号数组查询员工信息
     * @param deptnos
     * @return
     */
    List<Emp> findByDeptnoArray(int[] deptnos);

映射文件中使用foreach:

    <!--
    collection:  array表示数组 list表示集合
    open:       闭合的前缀
    close:      闭合的后缀
    separator:  中间元素的分割符
    item:       临时元素的变量名
    -->
    <select id="findByDeptnoArray" resultType="emp">
        select * from emp where deptno in
        <foreach collection="array" open="(" close=")" separator="," item="deptno">
            #{deptno}
        </foreach>
    </select>

测试方法:

    // 根据部门编号数组查询员工信息 -- foreach
    @Test
    public void test6() {
        EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
        List<Emp> result = mapper.findByDeptnoArray(new int[]{10, 20});
        result.forEach(System.out::println);
    }

MyBatis的标签使用就到此结束了

项目地址:

https://gitee.com/aruba/mybatis_study.git

有关MyBatis--动态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

随机推荐