帮我使用mybatis写一个分步查询查询员工表和部门表
时间: 2024-01-12 15:03:12 浏览: 71
1. 创建 Employee 实体类和 Department 实体类,分别对应员工表和部门表的结构。
Employee.java
```
public class Employee {
private int id;
private String name;
private int age;
private int departmentId;
// getter/setter 省略
}
```
Department.java
```
public class Department {
private int id;
private String name;
// getter/setter 省略
}
```
2. 创建 EmployeeMapper 接口和 DepartmentMapper 接口,用于定义查询方法。
EmployeeMapper.java
```
public interface EmployeeMapper {
// 根据员工 id 查询员工信息
Employee selectEmployeeById(int id);
// 根据部门 id 查询部门信息
Department selectDepartmentById(int id);
}
```
DepartmentMapper.java
```
public interface DepartmentMapper {
// 根据部门 id 查询部门信息
Department selectDepartmentById(int id);
}
```
3. 创建 EmployeeMapper.xml 和 DepartmentMapper.xml 文件,用于实现查询方法。
EmployeeMapper.xml
```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.EmployeeMapper">
<select id="selectEmployeeById" parameterType="int" resultType="com.example.entity.Employee">
SELECT * FROM employee WHERE id = #{id}
</select>
<select id="selectDepartmentById" parameterType="int" resultType="com.example.entity.Department">
SELECT * FROM department WHERE id = #{id}
</select>
</mapper>
```
DepartmentMapper.xml
```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.DepartmentMapper">
<select id="selectDepartmentById" parameterType="int" resultType="com.example.entity.Department">
SELECT * FROM department WHERE id = #{id}
</select>
</mapper>
```
4. 在配置文件中配置 mapper。
```
<configuration>
<mappers>
<mapper resource="com/example/mapper/EmployeeMapper.xml"/>
<mapper resource="com/example/mapper/DepartmentMapper.xml"/>
</mappers>
</configuration>
```
5. 在业务代码中使用分步查询。
```
@Autowired
private EmployeeMapper employeeMapper;
@Autowired
private DepartmentMapper departmentMapper;
public Employee getEmployeeById(int id) {
Employee employee = employeeMapper.selectEmployeeById(id);
Department department = departmentMapper.selectDepartmentById(employee.getDepartmentId());
employee.setDepartment(department);
return employee;
}
```
以上是使用 MyBatis 实现分步查询的步骤和代码示例,希望能对你有所帮助。
阅读全文