从mysql查询机构表用java解析成机构树

数据库表:
这里写图片描述

对应实体:

@Entity
@Table(name = "t_sys_org")
public class SysOrgDTO {
    private Long id;
    private String name;  
    private Long parentId;

    @Transient
    private List<SysOrgDTO> childOrg = new ArrayList<SysOrgDTO>();   
}

Controller层:

@RestController
@RequestMapping("/api/sys/org")
public class OrgController extends BaseController{
    @Autowired
    private OrgBO orgBO;
/**
     *机构树
     * @param orgId
     * @return
     */
    @RequestMapping(value = "/getOrgTree",method = RequestMethod.GET)
    @ApiOperation(value = "机构树",notes="机构树")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgId",value = "机构id",dataType = "Long",paramType = "query")
    })
    @ApiResponses(value = {@ApiResponse(code = 200,message = "机构树")})
    public JsonMessage<String> getOrgTree(@RequestParam(value = "orgId",required = false) Long orgId){
        return JsonMessage.successed(JsonUtil.toDefaultJSONString(orgBO.generateTreeNode(orgId),SysOrgDTO.getDefaultJsonFilter()));
    }
}

Service层:

@Service
public class OrgBO {
    @Autowired
    private SysOrgBO sysOrgBO;

    /**
     * 生成机构树
     * @param rootId
     * @return
     */
    public List<SysOrgDTO> generateTreeNode(Long rootId){
        List<SysOrgDTO> root = new ArrayList<SysOrgDTO>();
        if (rootId != null){
            //找到所有一级机构
            root = sysOrgBO.findAll(new NumberCondition("id",rootId,NumberCondition.Handler.EQUAL));
        }else {
            root = sysOrgBO.findAll(new NumberCondition("parentId",0,NumberCondition.Handler.EQUAL));
        }
        //为一级机构设置子机构
        for(SysOrgDTO org:root){
            org.setChildOrg(getChildNode(org.getId()));
        }
        return root;
    }

    /**
     * 根据父id查询所有子机构
     * @param nodeId
     * @return
     */
    public List<SysOrgDTO> getChildNode(Long nodeId){
        //根据父id查询子机构
        List<SysOrgDTO> childNodeList = sysOrgBO.findAll(new NumberCondition("parentId",nodeId,NumberCondition.Handler.EQUAL));
        //子机构下的子机构
        for(SysOrgDTO org:childNodeList){
            org.setChildOrg(getChildNode(org.getId()));//递归
        }
        if (childNodeList.size() == 0){
            return null;
        }
        return childNodeList;
    }
 }

这样返回的是一个list集合。

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页