国庆节10月1日
--


SpringBoot 三层架构实现部门列表查询,含驼峰命名映射与Nginx反向代理联调
部门查询功能用于查询所有部门数据并展示在部门管理页面中。基于 SpringBoot 三层架构(Controller → Service → Mapper)实现,涉及 MyBatis 字段映射、驼峰命名规则、请求方式限定以及前后端联调。
三层架构每一层的职责:

1@RestController2public class DeptController {3
4 @Autowired5 private DeptService deptService;6
7 @GetMapping("/depts")8 public Result list() {9 List<Dept> deptList = deptService.findAll();10 return Result.success(deptList);11 }12}限定请求方式有两种方法:
@RequestMapping(value = "/depts", method = RequestMethod.GET) — 通过 method 属性限定@GetMapping("/depts") — 使用衍生注解(推荐)| 请求方式 | 衍生注解 |
|---|---|
| GET | @GetMapping |
| POST | @PostMapping |
| PUT | @PutMapping |
| DELETE | @DeleteMapping |
1// DeptService 接口2public interface DeptService {3 public List<Dept> findAll();4}5
6// DeptServiceImpl 实现7@Service8public class DeptServiceImpl implements DeptService {9 @Autowired10 private DeptMapper deptMapper;11
12 public List<Dept> findAll() {13 return deptMapper.findAll();14 }15}1@Mapper2public interface DeptMapper {3 @Select("select * from dept")4 public List<Dept> findAll();5}当实体类属性名和数据库表字段名不一致时,MyBatis 不能自动封装。
例如数据库字段 create_time、update_time,实体类属性 createTime、updateTime。
三种解决方案:
1@Results({2 @Result(column = "create_time", property = "createTime"),3 @Result(column = "update_time", property = "updateTime")4})5@Select("select id, name, create_time, update_time from dept")6public List<Dept> findAll();1@Select("select id, name, create_time createTime, update_time updateTime from dept")2public List<Dept> findAll();如果字段名与属性名符合驼峰命名规则(abc_xyz → abcXyz),MyBatis 可自动映射。
1mybatis:2 configuration:3 map-underscore-to-camel-case: true前提:实体类属性与数据库字段名严格遵守驼峰命名规则。
前端工程通过 Nginx 反向代理访问后端 Tomcat 服务器。

请求访问流程:

Nginx 配置关键指令:
location:定义匹配特定 URI 请求的规则^~ /api/:精确匹配以 /api/ 开头的路径rewrite:重写匹配到的 URI 路径proxy_pass:代理转发,将匹配到的请求转发给后端服务器使用 Nginx 反向代理的原因:
@GetMapping 等衍生注解限定请求方式,简洁优雅@Results 手动映射仅在字段名无法自动映射时使用如果你喜欢,那么欢迎来到我的世界!
了解更多暂未播放



"所有的相遇都是久别重逢。"—— 未知


