Mybatis——example使用案例

1、案例:

@Test
public void getEmpListByExample(){
    //1.创建Example对象
    Example example = new Example(Employee.class);
    //2.通过Example对象创建Criteria对象
    Example.Criteria criteria01 = example.createCriteria();
    //5.执行查询
    List empList = employeeService.getEmpListByExample(example);

    for (Employee employee : empList) {
        System.out.println(employee);
    }
}

对应SQL:
SELECT emp_id,emp_name,emp_salary,emp_age FROM tabple_emp

2、案例:

@Test
public void getEmpListByExample(){
    //1.创建Example对象
    Example example = new Example(Employee.class);
    //排序
    example.setOrderByClause("emp_salary desc");
    //去重
    example.setDistinct(true);

    //2.通过Example对象创建Criteria对象
    Example.Criteria criteria01 = example.createCriteria();
    criteria01.andGreaterThan("empSalary",4000)
            .andGreaterThan("empAge",38);

    //5.执行查询
    List empList = employeeService.getEmpListByExample(example);
    for (Employee employee : empList) {
        System.out.println(employee);
    }
}

对应SQL:

SELECT distinct emp_id,emp_name,emp_salary,emp_age FROM tabple_emp WHERE ( emp_salary > ? and emp_age > ? ) order by emp_salary desc 

3、案例:or条件

@Test
    public void getEmpListByExample(){

        //1.创建Example对象
        Example example = new Example(Employee.class);
        //排序
        example.setOrderByClause("emp_salary desc");
        //去重
        example.setDistinct(true);

        //2.通过Example对象创建Criteria对象
        Example.Criteria criteria01 = example.createCriteria();
        criteria01.andGreaterThan("empSalary",4000)
                .andGreaterThan("empAge",38);
        //方法一:
//       example.or().andLessThan("empSalary",200)
//               .andLessThan("empAge",10);
       //方法二:
        Example.Criteria criteria02 = example.createCriteria();
        criteria02.andLessThan("empSalary",200)
                .andLessThan("empAge",10);
        example.or(criteria02);
        //5.执行查询
        List empList = employeeService.getEmpListByExample(example);

        for (Employee employee : empList) {
            System.out.println(employee);
        }
    }

对应SQL:

SELECT distinct emp_id,emp_name,emp_salary,emp_age FROM tabple_emp 
WHERE ( emp_salary > ? and emp_age > ? ) or ( emp_salary < ? and emp_age < ? ) order by emp_salary desc

你可能感兴趣的:(Mybatis)