关于项目中-----多级目录/菜单接口的写法(第二章MVC篇)
接着上篇–这篇是相关mvc的写法
看完了TestMapper.xml 紧接着看 接口TestMapper 我这里的SpringBoot整合了Mybatis.
首先是POJO:
Test:
@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel(description = "城市")
public class Test {
@ApiModelProperty(value = "城市id",position = 1)
private Integer id;
@ApiModelProperty(value = "城市名称",position = 2)
private String name;
@ApiModelProperty(value = "城市父id",position = 3)
private Integer parent_id;
@ApiModelProperty(value = "子类集合",position = 4)
private List<Test> zchilds =new ArrayList<>() ;
}
Dao层:
@Repository
public interface TestMapper {
List<Test> findAllTestData(int id);
}
然后是Service层
接口 ITestService:
import com.bobo.cd2006swagger.pojo.Test;
import java.util.List;
public interface ITestService {
Test findAllTestData(int id);
}
TestService:
@Service
public class TestService implements ITestService{
@Autowired
private TestMapper testMapper;
@Override
public Test findAllTestData(int id) {
List<Test> allTestData = testMapper.findAllTestData(id);
//创建一个map用于存放查询出来得数据
Map<Integer,Test> testMap = new HashMap();
for (Test t1: allTestData) {
testMap.put(t1.getId(),t1);
}
//创建一个lsit用于存放最终数据
List<Test> endTestData = new ArrayList<>();
for(Test t2 : allTestData){
if(null != t2.getParent_id()){
if(t2.getParent_id() == 0){
endTestData.add(t2);
}else {
Test test = testMap.get(t2.getParent_id());
List<Test> childs = test.getZchilds();
childs.add(t2);
}
}
}
return endTestData.get(0);
}
}
Service需要对查询出来的数据进行处理,毕竟后端对接口还是有着优雅的要求的,
Service对查询出来的数据
处理:
- 1.首先查询出来的数据以List形势接收着
List<Test> allTestData = testMapper.findAllTestData(id);
- 2.然后创建一个map集合用于存放查询出来的数据(后边有用)
//创建一个map用于存放查询出来得数据
Map<Integer,Test> testMap = new HashMap();
for (Test t1: allTestData) {
testMap.put(t1.getId(),t1);
}
- 3.创建一个list集合用于存放最后的数据
//创建一个lsit用于存放最终数据
List<Test> endTestData = new ArrayList<>();
- 4.遍历第一个集合,判断是否存在parent_id父类型ID 如果有则从map中取出然后将本身添加进对应的子集合中
for(Test t2 : allTestData){
if(null != t2.getParent_id()){
if(t2.getParent_id() == 0){
endTestData.add(t2);
}else {
Test test = testMap.get(t2.getParent_id());
List<Test> childs = test.getZchilds();
childs.add(t2);
}
}
}
最后是controller层
/**
* @author 阿伟
* ClassName: TestController
* date: 2020/12/27 16:46
* Description:
*/
@RestController
@Api(tags = "多级菜单测试模块")
public class TestController {
@Autowired
private ITestService testService;
@RequestMapping(value = "/findAllTestData.action",method = RequestMethod.GET)
@ApiOperation(value = "查询所有城市和其子城市")
@ApiImplicitParam(name = "id" ,value = "一级目录的城市id", dataType = "int", paramType = "query",required = true)
public Test findAllTestData(@RequestParam(value = "id")int id){
Test allTestData = testService.findAllTestData(id);
return allTestData;
}
}
最后swagger展示结果为
这就能很优雅的展示接口了