一.查询部门-需求
二.查询部门-思路
API接口文档
三.代码实现
1.controller层:负责与前端进行交互,接收前端所发来的请求
注:Slf4j用于记录日志使用,可以省略private static Logger log = LoggerFactory.getLogger(DeptController.class);这行代码从而直接调用log对象。
注:@RequestMapping(value = "/depts",method = RequestMethod.GET) 指定请求方式为GET
但是这种请求方式过于麻烦,因此使用@GetMapping()注解,其含义也是请求方式为Get
package com.gjw.controller;
/**
* 部门管理Controller
*/
import com.gjw.anno.Log;
import com.gjw.pojo.Dept;
import com.gjw.pojo.Result;
import com.gjw.service.DeptService;
import com.gjw.service.impl.DeptServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Slf4j // 记录日志使用
@RestController
public class DeptController {
@Autowired
private DeptService deptService;
// @RequestMapping(value = "/depts",method = RequestMethod.GET) 指定请求方式为GET
@GetMapping("/depts") // 指定请求方式为GET
public Result list(){
log.info("查询全部部门数据");
// 调用service层查询全部部门数据
List<Dept> deptList = deptService.list();
return Result.success(deptList);
}
}
设置Controller层接收前端发来的Get请求方式,url请求地址为/depts的请求后,controller层负责调用service层,由service层进行逻辑处理。因此通过依赖注入@Autowired来注入Service层的对象deptService。最后返回给前端的是一个统一响应结果Result。Result中封装的数据是查询出来的全部部门数据,封装在一个list集合当中。
2.service层:用来进行逻辑处理,并连接dao层,将从Dao层获得到的数据返回给controller层
service层接口:
package com.gjw.service;
import com.gjw.pojo.Dept;
import java.util.List;
public interface DeptService {
List<Dept> list();
}
service层实现类:
package com.gjw.service.impl;
import com.gjw.mapper.DeptLogMapper;
import com.gjw.mapper.DeptMapper;
import com.gjw.mapper.EmpMapper;
import com.gjw.pojo.Dept;
import com.gjw.pojo.DeptLog;
import com.gjw.service.DeptLogService;
import com.gjw.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;
@Service
public class DeptServiceImpl implements DeptService {
@Autowired
private DeptMapper deptMapper;
@Override
public List<Dept> list() {
return deptMapper.list();
}
}
service层中的list方法使用注入的deptMapper对象调用list方法来进行数据的获取。
3.Dao层:连接数据库进行数据的获取并返回给service层
package com.gjw.mapper;
import com.gjw.anno.Log;
import com.gjw.pojo.Dept;
import org.apache.ibatis.annotations.*;
import java.util.List;
/**
* 部门管理
*/
@Mapper
public interface DeptMapper {
/**
* 查询全部部门数据
* @return
*/
@Select("select * from dept")
List<Dept> list();
}