【Mybatis】SP03 通用Mapper QBC查询

QBC 全称 QueryByCriteria 

按照标准化的条件执行查询

 

筛选的条件被封装到Criteria集中处理

测试类:

@Test
public void qbcTest01() {
    // SQL 筛选 (WHERE emp_salary > ? AND emp_age < ? )|| WHERE emp_salary < ? AND emp_age > ? )
    // 创建一个例子实例,该实例至少注入一个实体类的字节对像
    Example employeeExample = new Example(Employee.class);
    // 创建查询的筛选条件
    Example.Criteria criteria01 = employeeExample.createCriteria();
    Example.Criteria criteria02 = employeeExample.createCriteria();
    // 返回值是这个THIS实例,
    criteria01.andGreaterThan("salary", 3000);
    criteria01.andLessThan("age", 22);
    // 条件实例2
    criteria02.andGreaterThan("salary", 5000).andGreaterThan("age", 30);
    employeeExample.or(criteria02);
    List<Employee> employeeList = employeeMapper.selectByExample(employeeExample);
    for (Employee employee : employeeList) {
        System.out.println(employee);
    }
}

日志打印:

DEBUG [main] - ==>  Preparing: SELECT emp_id,emp_name,emp_salary,emp_age FROM tabple_emp WHERE ( emp_salary > ? and emp_age < ? ) or ( emp_salary > ? and emp_age > ? )
DEBUG [main] - ==> Parameters: 3000(Integer), 22(Integer), 5000(Integer), 30(Integer)
DEBUG [main] - <==      Total: 2
Employee(id=2, name=jerry, salary=6635.42, age=38)
Employee(id=3, name=bob, salary=5560.11, age=40)

好奇的地方是在于,例子实例并没有对criteria进行任何处理,就这样被执行到了

哦,Criteria是内嵌的对象,返回自己就行了

 

其他查询的属性:

// 字段排序操作
employeeExample.orderBy("dsds").asc().orderBy("sadaas").desc();
// 记录去重 employeeExample.setDistinct(true);
// 设置仅查询的字段 employeeExample.selectProperties("p1", "p2", "p3");

 

posted @ 2020-08-27 14:42  emdzz  阅读(479)  评论(0)    收藏  举报