【项目实战】从 0 到 1 构建智能协同云图库(二):项目后端初始化
目录
1. 数据库环境搭建
2. 后端技术选型与依赖
3. 核心配置初始化
3.1 统一异常处理
3.2 分页插件配置
4. 关键通用封装
4.1 统一返回对象 BaseResponse
4.2 业务错误码枚举 ErrorCode
5. 项目运行与测试
总结
1. 数据库环境搭建
在项目开始前,我们需要准备好核心的数据库表。本项目使用 MySQL 8.0。
核心用户表设计:
SQL
-- 创建库 create database if not exists yupicture; use yupicture; -- 用户表 create table if not exists user ( id bigint auto_increment comment 'id' primary key, userAccount varchar(256) not null comment '账号', userPassword varchar(512) not null comment '密码', userName varchar(256) null comment '用户昵称', userAvatar varchar(1024) null comment '用户头像', userProfile varchar(512) null comment '用户简介', userRole varchar(256) default 'user' not null comment '用户角色:user/admin', createTime datetime default CURRENT_TIMESTAMP not null comment '创建时间', updateTime datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', isDelete tinyint default 0 not null comment '是否删除', index idx_userAccount (userAccount) ) comment '用户' collate = utf8mb4_unicode_ci;2. 后端技术选型与依赖
项目基于Spring Boot 2.7.x架构。在pom.xml中,除了基础的 Web Starter,我们重点引入以下依赖:
MyBatis-Plus:极大地简化 CRUD 操作。
Lombok:通过注解消除冗长的 Getter/Setter。
Gson/Hutool:强大的 JSON 处理与工具类库。
Knife4j:自动生成 Swagger 接口文档,方便调试。
3. 核心配置初始化
3.1 统一异常处理
为了保证接口返回的稳定性,我们定义了全局异常处理器,捕获业务异常并返回友好的 JSON 信息。
Java
@RestControllerAdvice @Slf4j public class GlobalExceptionHandler { @ExceptionHandler(BusinessException.class) public BaseResponse<?> businessExceptionHandler(BusinessException e) { log.error("BusinessException", e); return ResultUtils.error(e.getCode(), e.getMessage()); } }3.2 分页插件配置
MyBatis-Plus 默认的分页是逻辑分页,为了支持数据库物理分页,必须显式配置拦截器:
Java
@Configuration @MapperScan("com.yupi.yupicturebackend.mapper") public class MyBatisPlusConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return interceptor; } }4. 关键通用封装
4.1 统一返回对象BaseResponse
所有的接口统一返回BaseResponse,包含状态码、数据体和消息。
Java
public class BaseResponse<T> implements Serializable { private int code; private T data; private String message; }4.2 业务错误码枚举ErrorCode
定义清晰的错误码(如40100未登录、40300无权限),方便前后端联调。
5. 项目运行与测试
配置文件:在
application.yml中配置数据源与 MyBatis-Plus 日志输出,方便在控制台查看生成的 SQL。代码生成:使用 MyBatis-Plus Generator 或手动创建对应的 Mapper、Service、Controller。
启动:运行
MainApplication,访问/doc.html查看 Knife4j 自动生成的接口文档。
总结
本章我们完成了从数据库到后端工程骨架的搭建。通过统一的响应封装和分页配置,我们为后续开发高效、规范的代码打下了坚实基础。
下一章预告:我们将实现用户注册与登录的核心逻辑,并引入 AOP 实现细粒度的权限控制。
提示:在实际开发中,记得在application.yml中配置好数据库的username和password,否则启动会报错哦!
