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();
    }
    }

  • 相关阅读:
    react路由传参的三种方式:
    毕设登录逻辑分析
    redis缓存数据库的配置和分析
    c#窗体虚线图形验证码设计
    C#窗体技巧
    关于子窗体的层级关系
    安装SQL SERVER开启SA用户登录的方法
    SQL中CONVERT日期不同格式的转换用法
    sql server中自连接的使用
    IFieldEdit Interface 接口
  • 原文地址:https://www.cnblogs.com/zhangzhiqin/p/8565521.html
Copyright © 2011-2022 走看看