前要
项目设计–宿舍管理系统
文章目录
- 项目建立
- 导入依赖
- 配置文件
- 配置目录结构
- config配置
- mybatis-plus
- swagger
- 生成实体、mapper和service
- baseEntity
- 统一响应实例
- 响应码接口
- 响应码接口实现
- 统一响应result
- 统一分页响应
项目建立
太长了,修改一下
导入依赖
暂时先加上下面依赖,还有的话以后在看
<java.version>17</java.version><maven.compiler.source>17</maven.compiler.source><maven.compiler.target>17</maven.compiler.target><hutool.version>5.8.15</hutool.version><druid.version>1.2.16</druid.version><mybatis-plus.version>3.5.3.1</mybatis-plus.version><xxl-job.version>2.4.0</xxl-job.version><java-jwt.version>4.2.1</java-jwt.version><easyexcel.version>3.2.1</easyexcel.version><easy-captcha.version>1.6.2</easy-captcha.version><knife4j.version>4.0.0</knife4j.version><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId></dependency><!--mybatis-plus依赖--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>${mybatis-plus.version}</version></dependency><!--jwt令牌--><dependency><groupId>com.auth0</groupId><artifactId>java-jwt</artifactId><version>${java-jwt.version}</version></dependency><!--连接池--><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>${druid.version}</version></dependency><!--hutool工具包--><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>${hutool.version}</version></dependency><!--xxl-job定时任务--><dependency><groupId>com.xuxueli</groupId><artifactId>xxl-job</artifactId><version>${xxl-job.version}</version></dependency><!--excel操作--><dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>${easyexcel.version}</version></dependency><!-- 验证码 --><dependency><groupId>com.github.whvcse</groupId><artifactId>easy-captcha</artifactId><version>${easy-captcha.version}</version></dependency><!--swagger--><dependency><groupId>com.github.xiaoymin</groupId><artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId><version>${knife4j.version}</version></dependency>
配置文件
application.yml
spring:application:name: xiaoyuprofiles:active: dev
application-dev.yml
server:port: 8080spring:datasource:type: com.alibaba.druid.pool.DruidDataSourcedriver-class-name: com.mysql.cj.jdbc.Driverurl: username: password: data:redis:database: 6host: port: password: timeout: 10slettuce:pool:# 连接池最大连接数 默认8 ,负数表示没有限制max-active: 8# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认-1max-wait: -1# 连接池中的最大空闲连接 默认8max-idle: 8# 连接池中的最小空闲连接 默认0min-idle: 0
mybatis-plus:global-config:db-config:# 主键ID类型id-type: none# 逻辑删除字段名称logic-delete-field: deleted# 逻辑删除-删除值logic-delete-value: 1# 逻辑删除-未删除值logic-not-delete-value: 0configuration:# 驼峰下划线转换map-underscore-to-camel-case: true# 这个配置会将执行的sql打印出来,在开发或测试的时候可以用log-impl: org.apache.ibatis.logging.stdout.StdOutImpl# 认证配置
auth:token:secret_key: # token 有效期(单位:秒)ttl: # springdoc配置: https://springdoc.org/properties.html
springdoc:swagger-ui:enabled: trueoperationsSorter: alphatags-sorter: alphaapi-docs:enabled: true# 验证码配置
easy-captcha:# 验证码类型: arithmetic-算术type: arithmetic# 验证码有效时间(单位:秒)ttl: 120# xxl-job 定时任务配置
xxl:job:admin:# 多个地址使用,分割addresses:accessToken:executor:appname: address:ip:port: logpath:logretentiondays: # 系统配置
system:config:# 数据权限开关data-permission-enabled: # 定时任务 xxl-job 开关xxl-job-enabled: # WebSocket 开关websocket-enabled:
配置目录结构
新加一个handler包,用于像mybatis自动填充的处理配置
config配置
mybatis-plus
具体配置mybaits-plus配置
注解
// 配置文件
@Configuration
// 开启事务管理
@EnableTransactionManagement
// mapper扫描
@MapperScan("com.yu.mapper")
插件bean
这里先只配置分页插件
@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();//分页插件interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));return interceptor;}
自动填充bean
@Beanpublic GlobalConfig globalConfig() {GlobalConfig globalConfig = new GlobalConfig();globalConfig.setMetaObjectHandler(new MyMetaObjectHandler());return globalConfig;}
这里有2种写法,注释掉的是低版本的。高版本从3.3.0开始可以使用。不过3.3.0不要使用。有bug。
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {/*** 新增填充创建时间** @param metaObject*/@Overridepublic void insertFill(MetaObject metaObject) {
// this.strictInsertFill(metaObject, "createTime", LocalDateTime::now, LocalDateTime.class);
// this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);this.fillStrategy(metaObject,"createTime",LocalDateTime.now());this.fillStrategy(metaObject,"updateTime",LocalDateTime.now());}/*** 更新填充更新时间** @param metaObject*/@Overridepublic void updateFill(MetaObject metaObject) {
// this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);this.fillStrategy(metaObject,"updateTime",LocalDateTime.now());}}
swagger
@Configuration
public class SwaggerConfig {/*** 接口信息*/@Beanpublic OpenAPI apiInfo() {return new OpenAPI().components(new Components().addSecuritySchemes("Authorization",new SecurityScheme().type(SecurityScheme.Type.HTTP).scheme("bearer").bearerFormat("JWT"))).info(new Info().title("xiao-yu-Dormitory 接口文档").version("1.0.0").description("接口文档"));}/*** 系统接口分组*/@Beanpublic GroupedOpenApi systemApi() {String[] paths = {"/**"};String[] packagesToScan = {"com.yu.controller"};return GroupedOpenApi.builder().group("系统接口").packagesToScan(packagesToScan).pathsToMatch(paths).build();}}
生成实体、mapper和service
我直接用mybatisX进行生成
通过右键表可以
选择模块
基础包
baseEntity
在common包下新建一个类
用于规范创建和更新时间的类
@Data
public class BaseEntity implements Serializable {@Serialprivate static final long serialVersionUID = 1L;@TableField(fill = FieldFill.INSERT)@JsonInclude(value = JsonInclude.Include.NON_NULL)@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")private LocalDateTime createTime;@TableField(fill = FieldFill.INSERT_UPDATE)@JsonInclude(value = JsonInclude.Include.NON_NULL)@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")private LocalDateTime updateTime;
}
统一响应实例
响应码接口
public interface IResultCode {String getCode();String getMsg();}
响应码接口实现
@AllArgsConstructor
@NoArgsConstructor
public enum ResultCode implements IResultCode, Serializable {SUCCESS("00000", "ok"),@Overridepublic String getCode() {return code;}@Overridepublic String getMsg() {return msg;}private String code;private String msg;@Overridepublic String toString() {return "{" +"\"code\":\"" + code + '\"' +", \"msg\":\"" + msg + '\"' +'}';}public static ResultCode getValue(String code){for (ResultCode value : values()) {if (value.getCode().equals(code)) {return value;}}return SYSTEM_EXECUTION_ERROR; }
}
统一响应result
@EqualsAndHashCode(callSuper = true)
public record Result<T>(String code,T data,String msg
) implements Serializable{public static <T> Result<T> success() {return success(null);}public static <T> Result<T> success(T data) {return new Result<>(ResultCode.SUCCESS.getCode(),data,ResultCode.SUCCESS.getMsg());}public static <T> Result<T> failed() {return result(ResultCode.SYSTEM_EXECUTION_ERROR.getCode(), ResultCode.SYSTEM_EXECUTION_ERROR.getMsg(), null);}public static <T> Result<T> failed(String msg) {return result(ResultCode.SYSTEM_EXECUTION_ERROR.getCode(), msg, null);}public static <T> Result<T> judge(boolean status) {if (status) {return success();} else {return failed();}}public static <T> Result<T> failed(IResultCode resultCode) {return result(resultCode.getCode(), resultCode.getMsg(), null);}public static <T> Result<T> failed(IResultCode resultCode, String msg) {return result(resultCode.getCode(), msg, null);}private static <T> Result<T> result(IResultCode resultCode, T data) {return result(resultCode.getCode(), resultCode.getMsg(), data);}private static <T> Result<T> result(String code, String msg, T data) {return new Result<>(code, data, msg);}public static boolean isSuccess(Result<?> result) {return result != null && ResultCode.SUCCESS.getCode().equals(result.code());}
}
统一分页响应
public record PageResult<T>(String code,Data<T> data,String msg
) implements Serializable {public static <T> PageResult<T> success(IPage<T> page) {Data<T> data = new Data<T>(page.getRecords(), page.getTotal());return new PageResult<T>(ResultCode.SUCCESS.getCode(), data, ResultCode.SUCCESS.getMsg());}public record Data<T>(List<T> list, long total) {}}