通用Mapper(五)QBC查询

一、QBC 查询

  概念:

  Query By Criteria
  Criteria 是 Criterion 的复数形式,意思是规则、标准、准则。在SQL语句中相当于查询条件。
  QBC 查询是将查询条件通过java对象进行模块化封装。

  

二、案例

  1、使用QBC 进行查询

    /**
     * SELECT distinct emp_name , emp_salary FROM tabple_emp WHERE ( emp_salary > ? and emp_age < ? ) 
     * or ( emp_salary < ? and emp_age > ? ) order by emp_salary ASC,emp_age DESC   
     */
    @Test
    public void testSelectByExample() {
        //目标:where  (emp_salary>? and emp_age<?) or (emp_salary < ? and emp_age>?)
        //1.创建 Example对象
        Example example = new Example(Employee.class);

        //**********************
        //设置其他属性
        //1.设置排序信息
        example.orderBy("empSalary").asc().orderBy("empAge").desc();

        //2.设置 "去重"
        example.setDistinct(true);

        //3.设置select字段
        example.selectProperties("empName", "empSalary");

        //**********************

        //2. 通过 Example 对象创建 Criteria 对象
        Example.Criteria criteria1 = example.createCriteria();
        Example.Criteria criteria2 = example.createCriteria();

        //3. 在两个Criteria对象中分别设置查询条件
        //property:实体类的属性名      value:实体类的属性值
        criteria1.andGreaterThan("empSalary", 100.00).andLessThan("empAge", 25);

        criteria2.andLessThan("empSalary", 8000.00).andGreaterThan("empAge", 30);

        //4. 使用OR组装两个Criteria对象
        example.or(criteria2);

        //5.执行查询
        List<Employee> emp = employeeService.getEmpByExample(example);
        emp.forEach(System.out::println);
    }
    public List<Employee> getEmpByExample(Example example) {
        return employeeMapper.selectByExample(example);
    }

  2、

原文地址:https://www.cnblogs.com/niujifei/p/15269814.html