spring boot 连表查询返回树状结构的数据
时间: 2023-10-20 10:05:52 浏览: 176
对于返回树状结构的数据,可以使用递归查询来实现。在Spring Boot中,可以使用JPA或MyBatis等框架完成数据库操作。以下是一个示例,假设我们有一个Department和Employee两个实体类,它们之间是一对多的关系,一个部门可以有多个员工。
首先,定义一个DTO类,用于存储树状结构数据:
```
public class DepartmentDTO {
private Long id;
private String name;
private List<DepartmentDTO> children;
private List<Employee> employees;
// getter and setter
}
```
然后,定义一个DepartmentRepository接口:
```
public interface DepartmentRepository extends JpaRepository<Department, Long> {
@Query("select d from Department d where d.parent is null")
List<Department> findRootDepartments();
@Query("select d from Department d where d.parent.id = :parentId")
List<Department> findChildrenByParentId(@Param("parentId") Long parentId);
}
```
接下来,定义一个DepartmentService类,用于实现递归查询:
```
@Service
public class DepartmentService {
@Autowired
private DepartmentRepository departmentRepository;
public List<DepartmentDTO> getDepartmentTree() {
List<Department> rootDepartments = departmentRepository.findRootDepartments();
List<DepartmentDTO> departmentDTOS = new ArrayList<>();
for (Department rootDepartment : rootDepartments) {
DepartmentDTO departmentDTO = new DepartmentDTO();
departmentDTO.setId(rootDepartment.getId());
departmentDTO.setName(rootDepartment.getName());
departmentDTO.setEmployees(rootDepartment.getEmployees());
departmentDTO.setChildren(getChildren(rootDepartment.getId()));
departmentDTOS.add(departmentDTO);
}
return departmentDTOS;
}
private List<DepartmentDTO> getChildren(Long parentId) {
List<Department> children = departmentRepository.findChildrenByParentId(parentId);
List<DepartmentDTO> departmentDTOS = new ArrayList<>();
for (Department child : children) {
DepartmentDTO departmentDTO = new DepartmentDTO();
departmentDTO.setId(child.getId());
departmentDTO.setName(child.getName());
departmentDTO.setEmployees(child.getEmployees());
departmentDTO.setChildren(getChildren(child.getId()));
departmentDTOS.add(departmentDTO);
}
return departmentDTOS;
}
}
```
最后,在Controller中调用Service方法并返回数据即可:
```
@RestController
@RequestMapping("/departments")
public class DepartmentController {
@Autowired
private DepartmentService departmentService;
@GetMapping("/tree")
public List<DepartmentDTO> getDepartmentTree() {
return departmentService.getDepartmentTree();
}
}
```
这样就可以返回树状结构的数据了。需要注意的是,如果数据量比较大,递归查询可能会导致性能问题,可以考虑使用其他方式实现。
阅读全文