zoukankan      html  css  js  c++  java
  • trim配合prefix,prefixOverrides,suffix,suffixOverrides构建动态sql语句

    1.在接口构建方法

    public interface EmployeeMapperDynamicSQL {
    //携带了哪个字段查询条件就带上这个字段的值
    public List<Employee> getEmpsByConditionIf(Employee employee);

    }

    2在映射文件进行配置

    <!--public List<Employee> getEmpsByConditionTrim(Employee employee); -->
    <select id="getEmpsByConditionTrim" resultType="com.atguigu.mybatis.bean.Employee">
    select * from tbl_employee
    <!-- 后面多出的and或者or where标签不能解决
    prefix="":前缀:trim标签体中是整个字符串拼串 后的结果。
    prefix给拼串后的整个字符串加一个前缀
    prefixOverrides="":
    前缀覆盖: 去掉整个字符串前面多余的字符
    suffix="":后缀
    suffix给拼串后的整个字符串加一个后缀
    suffixOverrides=""
    后缀覆盖:去掉整个字符串后面多余的字符

    -->
    <!-- 自定义字符串的截取规则 -->
    <trim prefix="where" suffixOverrides="and">
    <if test="id!=null">
    id=#{id} and
    </if>
    <if test="lastName!=null &amp;&amp; lastName!=&quot;&quot;">
    last_name like #{lastName} and
    </if>
    <if test="email!=null and email.trim()!=&quot;&quot;">
    email=#{email} and
    </if>
    <!-- ognl会进行字符串与数字的转换判断 "0"==0 -->
    <if test="gender==0 or gender==1">
    gender=#{gender}
    </if>
    </trim>
    </select>

    3执行sql语句

    @Test
    public void testDynamicSql() throws IOException{
    SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
    SqlSession openSession = sqlSessionFactory.openSession();
    try{
    EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
    Employee employee = new Employee(null, "jerry2", null, null);
    //查询的时候如果某些条件没带可能sql拼装会有问题
    //1、给where后面加上1=1,以后的条件都and xxx.
    //2、mybatis使用where标签来将所有的查询条件包括在内。mybatis就会将where标签中拼装的sql,多出来的and或者or去掉
    //where只会去掉第一个多出来的and或者or。

    //测试Trim
    // List<Employee> emps2 = mapper.getEmpsByConditionTrim(employee);
    // for (Employee emp : emps2) {
    // System.out.println(emp);
    // }





    }finally{
    openSession.close();
    }
    }

  • 相关阅读:
    windows 下的 Apache SSL证书配置
    javascript xml字符串转为json对象
    php 服务端允许跨域访问
    前端自动化构建工具 gulp 学习笔记 一、
    mysql使用select语句导出表数据时,报error 1290解决方法
    批量操作系统服务的脚本(windows关闭服务脚本)
    Dism++备份还原系统
    Win10开启蓝屏信息记录及文件查看位置的方法
    MySql 8.0服务端安装后,用navicat12连接时报2059错误_解决
    软件测试之细节功能测试_注意点
  • 原文地址:https://www.cnblogs.com/zhangzhiqin/p/8565521.html
Copyright © 2011-2022 走看看