Mybatis联合查询的实现方法

数据库表结构

Mybatis联合查询的实现方法_第1张图片

department

employee

Mybatis联合查询的实现方法_第2张图片

Mybatis联合查询的实现方法_第3张图片

要求一

现在的要求是输入 id 把 employee 表的对应员工数据查询出来,并且查询出该员工的所处部门信息

public class Employee {
    private Integer id;
    private String lastName;
    private String email;
    private String gender;
    private Department dept;
	setter和getter.......
}
public class Department {
    private Integer id;
    private String departmentName;
    setter和getter.......
}

1、级联属性封装结果集

实现

这个要求很明显就要用到两个表,想要把部门信息封装到Employee对象的dept字段需要用到resultMap属性

方法一

 


	
	
	
	
	
	

方法二




	
	
	
	
	
		
		
	

测试

 	@Test
    public void test1() {
        SqlSession sqlSession = MyTest.getSqlSession();
        EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
        System.out.println(mapper.getEmployee(1));
    }

结果

2、分步查询

方法

DepartmentMapper.xml


EmployeeMaper.xml





	
	
	
	
	

测试

 	@Test
    public void test1() {
        SqlSession sqlSession = MyTest.getSqlSession();
        EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
        System.out.println(mapper.getEmployee2(1));
    }

结果

要求二

现在的要求是输入 id 把 department 表对应的部门信息查询出来,并且查询该部门下的所有员工信息

public class Employee {
    private Integer id;
    private String lastName;
    private String email;
    private String gender;
	setter和getter.......
}
public class Department {
    private Integer id;
    private String departmentName;
    private List employees;
    setter和getter.......
}

3、级联属性封装结果集

方法




	
	
	
		
		
		
		
	

测试

 	@Test
    public void test2() {
        SqlSession sqlSession = MyTest.getSqlSession();
        DepartmentMapper mapper = sqlSession.getMapper(DepartmentMapper.class);
        System.out.println(mapper.getDepartment(1));
    }

结果

4、分步查询

EmployeeMaper.xml


DepartmentMapper.xml




	
	
	

测试

 	@Test
    public void test2() {
        SqlSession sqlSession = MyTest.getSqlSession();
        DepartmentMapper mapper = sqlSession.getMapper(DepartmentMapper.class);
        System.out.println(mapper.getDepartment3(1));
    }

结果

到此这篇关于 Mybatis联合查询的实现方法的文章就介绍到这了,更多相关 Mybatis联合查询内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

你可能感兴趣的:(Mybatis联合查询的实现方法)