这里记录分享平时配置 springboot 的一些常用配置,有哪些地方错误的请大家改正
id int auto_increment primary key comment '自增主键' ,
create_time bigint not null comment '创建时间',
update_time bigint not null comment '更新时间',
version int default 0 not null comment '乐观锁',
deleted int default 0 not null comment '逻辑删除',
spring:
datasource:
url: jdbc:mysql://localhost:3306/funny_db?useSSL=false&charactorEncoding=utf8&serverTimezone=UTC
username: root
password: enncymysql
driver-class-name: com.mysql.cj.jdbc.Driver
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
return new DruidDataSource();
}
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.2.6version>
dependency>
https://blog.csdn.net/qq_31254489/article/details/119772129
https://blog.csdn.net/qq_31254489/article/details/119772338
记得使用 @EnableOpenApi
注解
@Configuration
@EnableOpenApi
public class GlobalConfig {
@Bean
public Docket createRestApi() {
ApiInfo apiInfo = new ApiInfoBuilder()
.title("SpringBoot-Swagger3")
.description("author : enncy")
.license("Apache-2.0")
.version("0.0.1")
.build();
return new Docket(DocumentationType.SWAGGER_2)
.useDefaultResponseMessages(false)
.apiInfo(apiInfo)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
//创建
.build();
}
}
@Configuration
@EnableOpenApi
@EnableWebSecurity
public class GlobalConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/**").permitAll();
}
}
@Data
@ApiModel(value = "基础实体对象", description = "基础实体对象")
public class BaseEntity {
@JSONField(serialize = false)
@ApiModelProperty(value = "自增主键", hidden = true)
@TableId(value = "id", type = IdType.AUTO)
public Integer id;
@JSONField(serialize = false)
@ApiModelProperty(value = "乐观锁", hidden = true)
@Version
public Integer version;
@JSONField(serialize = false)
@ApiModelProperty(value = "逻辑删除", hidden = true)
@TableLogic
public Integer deleted;
@ApiModelProperty(value = "插入时间", hidden = true)
@TableField(fill = FieldFill.INSERT)
public Long createTime;
@ApiModelProperty(value = "更新时间", hidden = true)
@TableField(fill = FieldFill.INSERT_UPDATE)
public Long updateTime;
}
子类控制器继承,并且传入指定的泛型,即可实现下面全部的接口
public class ServiceController<T extends BaseEntity> {
protected IService<T> service;
public ServiceController(IService<T> service) {
this.service = service;
}
@ApiOperation("根据id查询实体")
@GetMapping("/get/one")
public T selectById(@RequestParam("id") int id){
return service.getById(id);
}
@ApiOperation("获取全部信息")
@GetMapping("/get/all")
public List<T> selectAll(){
return service.list();
}
@ApiOperation("根据数量查询")
@GetMapping("/get/page")
public List<T> selectPage(@RequestParam("current") int current, @RequestParam("size") int size){
return service.page(new Page<>(current,size)).getRecords();
}
@ApiOperation("保存信息")
@PostMapping("/insert")
public boolean save(@RequestBody T target){
return service.save(target);
}
@ApiOperation("根据id更新")
@PostMapping("/update")
public boolean updateById(@RequestBody BaseDto<T> dto){
dto.target.setId(dto.getId());
return service.updateById(dto.target);
}
@ApiOperation("根据id删除")
@GetMapping("/delete")
public boolean removeById(@RequestParam("id") int id){
return service.removeById(id);
}
@ApiOperation("查询数量")
@GetMapping("/count")
public int count(){
return service.count();
}
}
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 最新版 mybatis 分页器
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
// 乐观锁
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
// 起始版本 3.3.0(推荐使用)
this.strictInsertFill(metaObject, "createTime", Long.class, System.currentTimeMillis());
this.strictUpdateFill(metaObject, "updateTime", Long.class, System.currentTimeMillis());
}
@Override
public void updateFill(MetaObject metaObject) {
// 起始版本 3.3.0(推荐)
this.strictUpdateFill(metaObject, "updateTime", Long.class, System.currentTimeMillis());
}
}
/**
* 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
*
Created in 10:45 2021/8/16
*
* @author: enncy
*/
@SpringBootTest
public class MyCodeGenerator {
@Autowired
DruidDataSource dataSource;
// 作者名
private static final String author = "enncy";
// 模块名
private static final String module = "test";
// 包名
private static final String packageName = "cn.enncy";
// 要生成的表名
private static final String[] tableNames = {"user"};
@Test
public void generate() {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor(author);
gc.setOpen(false);
gc.setFileOverride(false); // 是否覆盖
gc.setServiceName("%sService"); // 去掉 Service 的I前缀
gc.setIdType(IdType.AUTO);
gc.setDateType(DateType.ONLY_DATE);
gc.setSwagger2(true);// 实体属性 Swagger2 注解
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl(dataSource.getUrl());
dsc.setDriverName(dataSource.getDriverClassName());
dsc.setUsername(dataSource.getUsername());
dsc.setPassword(dataSource.getPassword());
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(module);
pc.setParent(packageName);
mpg.setPackageInfo(pc);
// 自动填充配置
TableFill createTime = new TableFill("create_time", FieldFill.INSERT);
TableFill updateTime = new TableFill("update_time", FieldFill.INSERT_UPDATE);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude(tableNames)
.setNaming(NamingStrategy.underline_to_camel) // 下划线转驼峰
.setColumnNaming(NamingStrategy.underline_to_camel)
.setEntityLombokModel(true) // 开启lombok
.setLogicDeleteFieldName("deleted") // 逻辑删除
.setSuperEntityClass(BaseEntity.class) // 实体父类
.setSuperControllerClass(ServiceController.class) // 控制器父类
.setRestControllerStyle(true) // 设置 restful 风格
.setTableFillList(Arrays.asList(createTime, updateTime)) // 自动填充
.setVersionFieldName("version"); // 乐观锁
mpg.setStrategy(strategy);
mpg.execute();
}
}
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.2.6version>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.4.3.1version>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-generatorartifactId>
<version>3.4.1version>
dependency>
<dependency>
<groupId>org.apache.velocitygroupId>
<artifactId>velocity-engine-coreartifactId>
<version>2.2version>
dependency>
<dependency>
<groupId>io.swaggergroupId>
<artifactId>swagger-annotationsartifactId>
<version>1.5.20version>
dependency>
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-boot-starterartifactId>
<version>3.0.0version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.78version>
dependency>