MyBatis实现连表查询操作
MyBatis实现连表查询操作
有时候一张表无法获取我们想要查询的所有信息,此时就需要使用连表查询的方式。
在MyBatis中如何实现连表查询?
这里根据数据库中员工表(Employee)和部门表(Department)
实体类:
部门实体类:
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Department {
private Integer did;
private String dname;
private String loc;
//部门里存放学生信息
private List<Employee> employeeList = new ArrayList<Employee>();
}
员工实体类:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
private Integer eid;
private String ename;
private Integer age;
private Double sal;
private Integer dept_id;
private String gender;
//专门存放员工里的部门信息
private Department department;
}
多对一操作
查询语句:根据id查询员工信息以及该员工对应的班级信息
举个例子:
(1)接口dao的内容
public interface EmployeeDao {
//根据id查询员工信息以及该员工对应的部门信息
public Employee employeeInfo(Integer id);
}
(2)mapper文件的内容
(3)测试代码
public class EmployeeTest {
@Test
public void queryById()throws Exception{
Reader resourceAsReader = Resources.getResourceAsReader("mybatis.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsReader);
SqlSession sqlSession = sqlSessionFactory.openSession();
EmployeeDao employeeDao = sqlSession.getMapper(EmployeeDao.class);
Employee employee = employeeDao.employeeInfo(2);
System.out.println("employee = " + employee);
}
效果展示:
一对多操作
查询语句:根据部门id查询部门的信息以及对应员工的信息
举个例子:
(1)接口dao的内容
public interface DepartmentDao {
//根据部门did查询对应的员工
public Department queryById(Integer id);
}
(2)mapper文件中的内容
(3)测试代码
public class DepartmentTest {
@Test
public void queryById()throws Exception{
Reader resourceAsReader = Resources.getResourceAsReader("mybatis.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsReader);
SqlSession sqlSession = sqlSessionFactory.openSession();
DepartmentDao departmentDao = sqlSession.getMapper(DepartmentDao.class);
Department department = departmentDao.queryById(2);
System.out.println("department = " + department);
}
}
效果展示: