Mybaitis案例二:员工信息查询系统(动态SQL)

在数据库建立一个employee表,实现以下功能:(基于案例一)

1.实现多条件查询,根据员工的姓名和年龄筛选
(1)当用户输入姓名不为空,年龄为空时,则只根据姓名查询;
(2)当用户输入年龄不为空,姓名为空时,则只根据年龄查询;
(3)当用户输入年龄和姓名都不为空时,根据年龄姓名同时查询;

(4)当用户输入年龄和姓名都为空时,则查询出所有职位不为空的的员工信息;
2.查询id=1,2,5,6的员工信息

3.单条件查询出所有id值小于5的员工的信息;

4.查询出年龄为26且职位为员工的员工信息;

代码实现:

使用了MyBatis动态SQL中的常用元素

1.EmployeeMapper.xml文件


    
    
    
    
    
    
    
    

2.测试类findTest

public class findTest {
    SqlSession sqlSession = MyBatisUtils.getSession();
    @Test
    public void findByNameOrAge(){
        Employee employee = new Employee();
        employee.setName("张三");
        employee.setAge(22);
        List list = sqlSession.selectList("findByNameOrAge",employee);
        for (Employee employee1:list){
            System.out.println(employee1);
        }
        sqlSession.close();
    }
    @Test
    public void findByArray(){
        Integer[] ids = {1,2,5,6};
        List list = sqlSession.selectList("findByArray",ids);
        for (Employee employee:list){
            System.out.println(employee);
        }
        //找不到的时候呢?
        sqlSession.close();
    }
    @Test
    public void findByList(){
        List list = new ArrayList<>();
        for (int i = 0;i < 5;i++){
            list.add(i);
        }
        List employees = sqlSession.selectList("findByList",list);
        for (Employee employee:employees){
            System.out.println(employee);
        }
        sqlSession.close();
    }
    @Test
    public void findByMap(){
        List list = new ArrayList<>();
        list.add(1);
        list.add(3);
        list.add(5);
        list.add(6);
        Map map = new HashMap<>();
        map.put("id",list);
        map.put("age","26");
        map.put("position","员工");
        List employees = sqlSession.selectList("findByMap",map);
        for (Employee employee:employees){
            System.out.println(employee);
        }
        sqlSession.close();
    }
}

你可能感兴趣的:(MyBatis学习梳理,sql,数据库,database)