803 字
4 分钟
部门查询功能
AI 摘要
部门查询功能
定义
部门查询功能用于查询所有部门数据并展示在部门管理页面中。基于 SpringBoot 三层架构(Controller → Service → Mapper)实现,涉及 MyBatis 字段映射、驼峰命名规则、请求方式限定以及前后端联调。
实现思路
三层架构每一层的职责:

- Controller 层:接收前端请求,调用 Service 查询部门数据,响应结果
- Service 层:调用 Mapper 接口方法,查询所有部门数据
- Mapper 层:执行查询所有部门数据的 SQL 操作
代码实现
Controller 层
@RestControllerpublic class DeptController {
@Autowired private DeptService deptService;
@GetMapping("/depts") public Result list() { List<Dept> deptList = deptService.findAll(); return Result.success(deptList); }}限定请求方式有两种方法:
@RequestMapping(value = "/depts", method = RequestMethod.GET)— 通过 method 属性限定@GetMapping("/depts")— 使用衍生注解(推荐)
| 请求方式 | 衍生注解 |
|---|---|
| GET | @GetMapping |
| POST | @PostMapping |
| PUT | @PutMapping |
| DELETE | @DeleteMapping |
Service 层
// DeptService 接口public interface DeptService { public List<Dept> findAll();}
// DeptServiceImpl 实现@Servicepublic class DeptServiceImpl implements DeptService { @Autowired private DeptMapper deptMapper;
public List<Dept> findAll() { return deptMapper.findAll(); }}Mapper 层
@Mapperpublic interface DeptMapper { @Select("select * from dept") public List<Dept> findAll();}数据封装 — 字段映射
当实体类属性名和数据库表字段名不一致时,MyBatis 不能自动封装。
例如数据库字段 create_time、update_time,实体类属性 createTime、updateTime。
三种解决方案:
方案一:手动结果映射(@Results + @Result)
@Results({ @Result(column = "create_time", property = "createTime"), @Result(column = "update_time", property = "updateTime")})@Select("select id, name, create_time, update_time from dept")public List<Dept> findAll();方案二:SQL 起别名
@Select("select id, name, create_time createTime, update_time updateTime from dept")public List<Dept> findAll();方案三:开启驼峰命名(推荐)
如果字段名与属性名符合驼峰命名规则(abc_xyz → abcXyz),MyBatis 可自动映射。
mybatis: configuration: map-underscore-to-camel-case: true前提:实体类属性与数据库字段名严格遵守驼峰命名规则。
前后端联调
前端工程通过 Nginx 反向代理访问后端 Tomcat 服务器。

请求访问流程:

Nginx 配置关键指令:
location:定义匹配特定 URI 请求的规则^~ /api/:精确匹配以/api/开头的路径rewrite:重写匹配到的 URI 路径proxy_pass:代理转发,将匹配到的请求转发给后端服务器
使用 Nginx 反向代理的原因:
- 安全:后端 Tomcat 集群不直接暴露给前端
- 灵活:后端增减服务器对前端无感知,只需修改 Nginx 配置
- 负载均衡:可方便实现后端 Tomcat 的负载均衡
常见场景
- 列表页数据加载,一次性查询全部记录并展示
- 前后端分离项目中,通过 Nginx 代理解决跨域和负载均衡
- 数据库下划线字段与 Java 驼峰属性之间的自动映射
注意事项
- 推荐使用
@GetMapping等衍生注解限定请求方式,简洁优雅 - 驼峰命名映射是最推荐的字段映射方案,但前提是命名严格遵循规范
@Results手动映射仅在字段名无法自动映射时使用- Nginx 的反向代理使前后端解耦,前端始终请求同一地址
相关链接
支持与分享
如果这篇文章对你有帮助,欢迎分享给更多人或赞助支持!
最后更新于 2026-05-21,距今已过 30 天
部分内容可能已过时
评论区
[ 标签 ]
[ 分类 ]
[ 公告 ]
如果你喜欢,那么欢迎来到我的世界!
了解更多[ 音乐 ]
找不到相关结果。
[ contents ]
[ 全部文章 ]