========================= MyBatis关联映射之一多关联 ========================= 部门->员工 1 数据表 1.1 部门 create table t_department( id int primary key auto_increment, <-- name varchar(30) not null unique, | description varchar(100) | ); | | 1.2 员工 | | create table t_employee( | number char(5) primary key, | fullname varchar(20) not null, | age int not null, | department int not null -------------- ); 2 实体类 2.1 部门 @Data @NoArgsConstructor @AllArgsConstructor @ToString public class Department { private int id; private String name; private String description; } 2.2 员工 @Data @NoArgsConstructor @AllArgsConstructor @ToString public class Employee { private String number; private String fullname; private int age; private int department; } 3 DAO 3.1 部门 public interface DepartmentDao { public int addDepartment(Department department); } 3.2 员工 public interface EmployeeDao { public int addEmployee(Employee employee); } 4 映射 4.1 部门 insert into t_department(name, description) values(#{name}, #{description}) 4.2 员工 insert into t_employee(number, fullname, age, department) values(#{number}, #{fullname}, #{age}, #{department}) 5 测试 public class DepartmentDaoTest { @Test public void testAddDepartment() { DepartmentDao departmentDao = MyBatisUtil.getMapper(DepartmentDao.class); Department department = new Department(0, "研发部", "研发软件产品", null); assertEquals(1, departmentDao.addDepartment(department)); EmployeeDao employeeDao = MyBatisUtil.getMapper(EmployeeDao.class); assertEquals(1, employeeDao.addEmployee( new Employee("1001", "张飞", 25, department.getId()))); assertEquals(1, employeeDao.addEmployee( new Employee("1002", "关羽", 30, department.getId()))); assertEquals(1, employeeDao.addEmployee( new Employee("1003", "赵云", 20, department.getId()))); } } 6 连接查询 @Data @NoArgsConstructor @AllArgsConstructor @ToString public class DepartmentEmployees { private Department department; private List employees; } public interface DepartmentDao { ... public DepartmentEmployees getDepartmentEmployees(String name); ... } ... ... ... ... public class DepartmentDaoTest { ... @Test public void testGetDepartmentEmployees() { DepartmentDao departmentDao = MyBatisUtil.getMapper(DepartmentDao.class); DepartmentEmployees departmentEmployees = departmentDao.getDepartmentEmployees("研发部"); assertNotEquals(null, departmentEmployees); System.out.println(departmentEmployees); } ... } 运行测试用例。 例程:Association 7 子查询 public interface EmployeeDao { ... public List getEmployees(int department); ... } ... ... ... ... 运行测试用例。 例程:Association