目录
一、创建父工程
- 添加
<packaging>pom</packaging>
<properties> 这里统一放版本号 </properties>
在子项目里添加启动类
@SpringBootApplication
public class EduApplication {
public static void main(String[] args) {
SpringApplication.run(EduApplication.class,args);
}
}
- 注意启动类的位置
二、整合其他技术
1、整合 mybatis-plus 持久层
<!--mybatis-plus 持久层-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<!-- velocity 模板引擎, Mybatis Plus 代码生成器需要 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>${velocity.version}</version>
</dependency>
public static void main(String[] args) {
// 1、创建代码生成器
AutoGenerator mpg = new AutoGenerator();
// 2、全局配置
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
//gc.setOutputDir(projectPath + "/src/main/java");
//代码生成的路径E:\学习\学习项目\硅谷课堂\ggkt_parent
gc.setOutputDir("E:\\programming\\java\\学习项目\\guli_paret\\service\\service_edu\\src\\main\\java");
gc.setServiceName("%sService"); //去掉Service接口的首字母I
gc.setAuthor("xbfinal");
gc.setOpen(false);
mpg.setGlobalConfig(gc);
// 3、数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/guli?serverTimezone=GMT%2B8");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");//数据库账号
dsc.setPassword("123456");//数据库密码
dsc.setDbType(DbType.MYSQL);
mpg.setDataSource(dsc);
// 4、包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.xbfinal");
pc.setModuleName("eduservice"); //模块名
pc.setController("controller");
pc.setEntity("entity");
pc.setService("service");
pc.setMapper("mapper");
mpg.setPackageInfo(pc);
// 5、策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("edu_teacher");
strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略
strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略
strategy.setEntityLombokModel(true); // lombok 模型 @Accessors(chain = true) setter链式操作
strategy.setRestControllerStyle(true); //restful api风格控制器
strategy.setControllerMappingHyphenStyle(true); //url中驼峰转连字符
mpg.setStrategy(strategy);
// 6、执行
mpg.execute();
}
@Configuration
@MapperScan("com.xbfinal.eduservice.mapper")
public class EduConfig {
/**
* 逻辑删除插件
*/
@Bean
public ISqlInjector sqlInjector(){
return new LogicSqlInjector();
}
}
分页功能
/**
* mp分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}
//创建page对象 参数1页码 参数2条数
Page<EduTeacher> page=new Page<>(current,limit);
//调用Service.page 方法实现分页 参数1 page对象 参数2 条件
IPage<EduTeacher> page1 = eduTeacherService.page(page, null);
//由于博客笔记原因 代码我就都写controller了
@PostMapping("pageTeacherCondition/{current}/{limit}")
public Result pageTeacherCondition(
@ApiParam(name = "current",value = "当前页码")
@PathVariable("current") Long current,
@ApiParam(name = "limit",value = "条数")
@PathVariable("limit") Long limit ,
@RequestBody(required = false) TeacherQuery teacherQuery){
//1.创建page对象
Page<EduTeacher> page=new Page<>(current,limit);
//构建条件wrapper
QueryWrapper<EduTeacher> wrapper = new QueryWrapper<>();
//多条件组合查询
String name=teacherQuery.getName();
if (!StrUtil.isEmpty(name)){
//模糊查询 参数1 数据库中字段的名称 参数2 条件
wrapper.like("name",name);
}
//调用Service.page 方法实现分页 参数1 page对象 参数2 条件
IPage<EduTeacher> page1 = eduTeacherService.page(page,wrapper );
return Result.ok().addData(page1);
}
2、整合swagger
3、 阿里云OSS存储服务
- 创建 oss的许可证
AccessKey
- 官方文档 SDK文档 不多说了很详细的文档 还有视频
配置文件
#阿里云 OSS
#服务器地址
aliyun.oss.file.endpoint=oss-cn-beijing.aliyuncs.com #(服务器地址)
aliyun.oss.file.keyid=AccessKey ID
aliyun.oss.file.keysecret=AccessKey Secret
#bucket可以在控制台创建,也可以用java创建
aliyun.oss.file.bucketname=xxxx # xxxx是 bucket的name
出现问题
- 解决方案一:可以在配置文件配置数据库
- 方案二(🎆):在启动类上添加属性,默认不去加载数据库 ======= == == = = = = = = == == =》
exclude = DataSourceAutoConfiguration.class
4、使用EasyExcel读取Excel内容
三、common模块
1.统一返回数据格式
- 写一个
interface
来定义成功和失败的状态码
/**
* @author 笑霸final
*/
public interface ResultCode {
/**
* 自定义成功的状态码
*/
public static Integer SUCCESS=20000;
/**
* 自定义失败的状态码
*/
public static Integer ERROR=20001;
}
- 创建统一返回结果类
Result
@Data
public class Result<T> {
@ApiModelProperty(value = "是否成功")
private Boolean success;
@ApiModelProperty(value = "状态码")
private Integer code;
@ApiModelProperty(value = "消息")
private String message;
@ApiModelProperty(value = "返回的数据")
private T data;
@ApiModelProperty(value = "动态数据")
private Map map = new HashMap();
/**
* 防止直接new
*/
private Result(){};
/**
* 成功的静态方法
*/
public static<T> Result<T> ok( ){
Result r=new Result();
r.success=true;
r.code=ResultCode.SUCCESS;
r.message="成功";
return r;
}
/**
* 失败的静态方法
*/
public static Result failed( ){
Result r=new Result();
r.success=false;
r.code=ResultCode.ERROR;
r.message="失败";
return r;
}
public Result addCode(Integer code){
this.setCode(code);
return this;
}
public Result addMessage(String message){
this.setMessage(message);
return this;
}
public Result<T> addData(T data){
this.setData(data);
return this;
}
/**
* 用来操作 map = new HashMap(); 动态数据
* @param key
* @param value
* @return
*/
public Result<T> add(String key, Object value) {
this.map.put(key, value);
return this;
}
}
2.数据自动填充
-
先给需要自动填充的数据加上注解
@TableField(fill = FieldFill.INSERT)
或者@TableField(fill = FieldFill.INSERT_UPDATE)
-
编写
MyMetaObjectHandler
类去实现MetaObjectHandler
接口
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
//属性名称,不是字段名称
this.setFieldValByName("gmtCreate", new Date(), metaObject);
this.setFieldValByName("gmtModified", new Date(), metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("gmtModified", new Date(), metaObject);
}
}
3.统一异常处理
全局异常处理
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
//全局异常处理
@ResponseBody//返回json数据
@ExceptionHandler(Exception.class)
public Result error(Exception e){
log.info("当前异常信息\n",e);
return Result.fail("全局异常处理");
}
}
自定义异常处理
public class GgktException extends RuntimeException{
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class GgktException extends RuntimeException{
private Integer code;//状态码
private String msg;//异常信息
}
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
@ResponseBody//返回json数据
@ExceptionHandler(Exception.class) //全局异常处理Exception.class
public Result error(Exception e){
log.info("当前异常信息\n",e);
return Result.fail("全局异常处理");
}
@ResponseBody
@ExceptionHandler(GgktException.class) //自定义的异常处理方法
public Result divError(GgktException e){
log.info("当前异常信息\n",e.getMsg());
return Result.fail("自定义的异常处理");
}
public Result<List<Teacher>> findAllTeacher(){
try{
int i=1/0;
}catch (Exception e){
//手动抛出异常
throw new GgktException(201,"执行了自定义异常处理");
}
List<Teacher> teacherList = teacherService.list();
return Result.ok(teacherList);
}