lombok
provided
org.apache.commons
commons-lang3
3.7
org.springframework.boot
spring-boot-starter-test
test
org.freemarker
freemarker
2.3.28
org.apache.velocity
velocity-engine-core
2.0
com.alibaba
druid
1.0.9
org.codehaus.jackson
jackson-mapper-asl
1.5.0
这里是我把后续要用到的依赖一起加上了,包含swagger,fastjson,jackson,freemarker,velocity,lombok等,当然最主要的是mybatis-plus-boot-starter,这里用的3.0.3 的版本算是比较新的了。引入它之后就不需要在添加mybatis 依赖了。
配置数据源 application.properties 中添加
spring.datasource.url=jdbc:mysql://localhost:3306/exchange?useUnicode=true&characterEncoding=gbk&useSSL=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
添加数据源配置类:
@Configuration
public class MybatisConfig {
@Bean
@ConfigurationProperties(prefix = “spring.datasource”)
public DataSource druidDataSource() {
return new DruidDataSource();
}
/**
-
分页拦截器
-
@return
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
使用一下MP 的代码生成功能:
创建代码生成器类:
package com.elens.data.rbces.mybatis;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
/**
-
@BelongsProject: rbc-es
-
@BelongsPackage: com.elens.data.rbces.mybatis
-
@Author: xuweichao
-
@CreateTime: 2019-04-10 17:08
-
@Description: 代码生成
*/
public class MysqlGenerator {
private static String projectPath = System.getProperty(“user.dir”);
//父包路径
private static String parentPackageName = “com.elens.data.rbces”;
//作者名字
private static String authorName = “xuweichao”;
/**
-
全局设置
-
@return
*/
public static GlobalConfig globalConfig() {
GlobalConfig globalConfig = new GlobalConfig();
globalConfig.setOutputDir(projectPath + “/src/main/java”)
// 是否支持 AR
.setActiveRecord(true)
//设置作者名字
.setAuthor(authorName)
//文件覆盖(全新文件)
.setFileOverride(true)
//主键策略
.setIdType(IdType.AUTO)
//SQL 映射文件
.setBaseResultMap(true)
//SQL 片段
.setBaseColumnList(true)
.setSwagger2(true)
.setEnableCache(false)
.setOpen(false)
//时间类型
.setDateType(DateType.ONLY_DATE)
.setEnableCache(false)
;
return globalConfig;
}
/**
-
数据源配置
-
@return
*/
public static DataSourceConfig dataSourceConfig() {
DataSourceConfig dataSourceConfig = new DataSourceConfig();
ResourceBundle rootResource = ResourceBundle.getBundle(“application”);
String url = rootResource.getString(“spring.datasource.url”);
String username = rootResource.getString(“spring.datasource.username”);
String password = rootResource.getString(“spring.datasource.password”);
String driverClassName = rootResource.getString(“spring.datasource.driver-class-name”);
dataSourceConfig
.setDbType(DbType.MYSQL)
.setUrl(url)
.setDriverName(driverClassName)
.setUsername(username)
// .setSchemaName(“public”)
.setPassword(password);
return dataSourceConfig;
}
/**
-
包名相关配置
-
@return
*/
public static PackageConfig packageConfig(String moduleName) {
PackageConfig packageConfig = new PackageConfig();
//配置父包路径
packageConfig.setParent(parentPackageName)
.setMapper(“mybatis.mapper”)
.setXml(“mybatis.mapper”)
.setEntity(“mybatis.entity”)
.setService(“service”)
//会自动生成 impl,可以不设定
.setServiceImpl(“service.impl”)
.setController(“controller”);
if (StringUtils.isNotEmpty(moduleName)) {
//配置业务包路径
packageConfig.setModuleName(moduleName);
}
return packageConfig;
}
/**
-
配置模板
-
@return
*/
public static InjectionConfig injectionConfig(String moduleName) {
InjectionConfig injectionConfig = new InjectionConfig() {
//自定义属性注入:abc
//在.ftl(或者是.vm)模板中,通过${cfg.abc}获取属性
@Override
public void initMap() {
// Map<String, Object> map = new HashMap<>();
// map.put(“abc”, this.getConfig().getGlobalConfig().getAuthor() + “-mp”);
// this.setMap(map);
}
};
// 自定义输出配置
List focList = new ArrayList<>();
// 如果模板引擎是 freemarker
String templatePath = “/templates/mapper.xml.ftl”;
// 如果模板引擎是 velocity
// String templatePath = “/templates/mapper.xml.vm”;
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
if (StringUtils.isEmpty(moduleName)) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + “/src/main/java/com/elens/data/rbces/mybatis/mapper/”
- tableInfo.getEntityName() + “Mapper” + StringPool.DOT_XML;
} else {
return projectPath + “/src/main/java/com/elens/data/rbces/mybatis/mapper/”
-
moduleName + “/”
-
tableInfo.getEntityName() + “Mapper” + StringPool.DOT_XML;
}
}
});
injectionConfig.setFileOutConfigList(focList);
return injectionConfig;
}
/**
-
生成策略配置
-
@param tableName
-
@return
*/
public static StrategyConfig strategyConfig(String moduleName, String… tableName) {
StrategyConfig strategyConfig = new StrategyConfig();
//设置命名规则 underline_to_camel 底线变驼峰
strategyConfig.setNaming(NamingStrategy.underline_to_camel)
//设置设置列命名 underline_to_camel 底线变驼峰
.setColumnNaming(NamingStrategy.underline_to_camel)
//设置继承类
//.setSuperEntityClass(“com.maoxs.pojo”)
//设置继承类
//.setSuperControllerClass(“com.maoxs.controller”)
//是否加入lombok
.setEntityLombokModel(true)
.setRestControllerStyle(true)
.setControllerMappingHyphenStyle(true)
//设置表名
.setInclude(tableName)
//设置超级列
// .setSuperEntityColumns(“id”)
//设置controller映射联字符
.setControllerMappingHyphenStyle(true)
//表的前缀
.setTablePrefix(packageConfig(moduleName).getModuleName() + “_”);
return strategyConfig;
}
/**
-
配置模板
-
@return
*/
public static TemplateConfig templateConfig() {
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
// templateConfig.setEntity(“templates/entity2.java”);
// templateConfig.setService();
templateConfig.setController("/templates/controller.java");
templateConfig.setXml(null);
return templateConfig;
}
public static void Generator(String moduleName, String… tableName) {
AutoGenerator mpg = new AutoGenerator()
.setCfg(injectionConfig(moduleName))
.setTemplate(templat
《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》
【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 完整内容开源分享
eConfig())
.setGlobalConfig(globalConfig())
.setDataSource(dataSourceConfig())
.setPackageInfo(packageConfig(moduleName))
.setStrategy(strategyConfig(moduleName, tableName))
// 选择 freemarker 引擎需要指定如下加,注意 pom 依赖必须有!默认 Veloctiy
.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
public static void main(String[] args) {
Generator(null, new String[]{“elens_report”});
}
}
这里有些包名,自定义的东西根据情况进行修改。
我这里对controller 类的生成做了一个模板,在/resources/templates 下创建controller.java.ftl
代码如下:
package ${package.Controller};
<#if restControllerStyle>
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.java.Log;
import org.springframework.web.bind.annotation.*;
<#else>
import org.springframework.stereotype.Controller;
</#if>
<#if superControllerClassPackage??>
import ${superControllerClassPackage};
</#if>
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import com.elens.data.rbces.vo.Wrapper;
import com.elens.data.rbces.vo.WrapMapper;
import com.elens.data.rbces.vo.QueryPageDto;
import package.Service.{package.Service}.package.Service.{table.serviceName};
import package.Entity.{package.Entity}.package.Entity.{entity};
/**
-
@author ${author}
-
@since ${date}
*/
<#if restControllerStyle??>
@Log
@Api(value="entity相关接口",tags="{entity} 相关接口",tags ="entity相关接口",tags="{entity} 相关接口")
@RestController
<#else>
@Controller
</#if>
@RequestMapping("<#if package.ModuleName??>KaTeX parse error: Expected 'EOF', got '#' at position 23: …e.ModuleName}</#̲if><#if control…{controllerMappingHyphen}<#else>${table.entityPath}</#if>")
<#if superControllerClass??>
public class ${table.controllerName} extends ${superControllerClass} {
<#else>
public class ${table.controllerName} {
</#if>
@Autowired
public ${table.serviceName} ${table.entityPath}Service;
/**
-
分页查询数据
-
@return
*/
@ApiOperation(value = “分页查询”, notes = “分页查询”)
@PostMapping(“getPage”)
public Wrapper get${entity}List(@RequestBody QueryPageDto queryPageDto){
log.info(“获取的参数:===>>” + queryPageDto);
Page<${entity}> page = new Page<>(queryPageDto.getPage(), queryPageDto.getSize());
try{
QueryWrapper<${entity}> queryWrapper = new QueryWrapper<>();
<#–queryWrapper.select(“user_name”, “user_company”);–>
<#–queryWrapper.like(“user_name”, “测试”);–>
<#–queryWrapper.ne(“user_company”, “”);–>
${table.entityPath}Service.pageMaps(page, queryWrapper);
}catch(Exception e){
e.printStackTrace();
return WrapMapper.error();
}
return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE, page);
}
/**
-
添加修改
-
@param ${table.entityPath}
-
@return
*/
@ApiOperation(value = “添加或修改”, notes = “根据id添加或修改”)
@PostMapping(“addUpd”)
public Wrapper table.entityPathAddUpd({table.entityPath}AddUpd(table.entityPathAddUpd({entity} ${table.entityPath}){
log.info(“获取的参数:===>>” + ${table.entityPath});
try{
table.entityPathService.saveOrUpdate({table.entityPath}Service.saveOrUpdate(table.entityPathService.saveOrUpdate({table.entityPath});
}catch(Exception e){
e.printStackTrace();
return WrapMapper.error();
}
return WrapMapper.ok();
}
/**
-
根据id删除对象
-
@param id 实体ID
*/
@ApiOperation(value = “删除”, notes = “根据id删除”)
@GetMapping(“del/{id}”)
public Wrapper ${table.entityPath}Delete(@PathVariable int id){
log.info(“获取的参数:===>>” + id);
try{
${table.entityPath}Service.removeById(id);
}catch(Exception e){
e.printStackTrace();
return WrapMapper.error();
}
return WrapMapper.ok();
}
}
其中包含了增删改,分页查询功能。
启动MysqlGenerator 类:
可见生成目录
文件名为红色的即为自动生成的文件。
controller 文件如下:
@Log
@Api(value=“ElensReport 相关接口”,tags =“ElensReport 相关接口”)
@RestController
@RequestMapping(“elens-report”)
public class ElensReportController {
@Autowired
public IElensReportService elensReportService;
/**
-
分页查询数据
-
@return
*/
@ApiOperation(value = “分页查询”, notes = “分页查询”)
@PostMapping(“getPage”)
public Wrapper getElensReportList(@RequestBody QueryPageDto queryPageDto){
log.info(“获取的参数:===>>” + queryPageDto);
Page page = new Page<>(queryPageDto.getPage(), queryPageDto.getSize());
try{
QueryWrapper queryWrapper = new QueryWrapper<>();
elensReportService.pageMaps(page, queryWrapper);
}catch(Exception e){
e.printStackTrace();
return WrapMapper.error();
}
return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE, page);
}
/**
-
添加修改
-
@param elensReport
-
@return
*/
@ApiOperation(value = “添加或修改”, notes = “根据id添加或修改”)
@PostMapping(“addUpd”)
public Wrapper elensReportAddUpd(ElensReport elensReport){
log.info(“获取的参数:===>>” + elensReport);
try{
elensReportService.saveOrUpdate(elensReport);
}catch(Exception e){
e.printStackTrace();
return WrapMapper.error();
}
return WrapMapper.ok();
}
/**
-
根据id删除对象
-
@param id 实体ID
*/
@ApiOperation(value = “删除”, notes = “根据id删除”)
@GetMapping(“del/{id}”)
public Wrapper elensReportDelete(@PathVariable int id){
log.info(“获取的参数:===>>” + id);
try{
elensReportService.removeById(id);
}catch(Exception e){
e.printStackTrace();
return WrapMapper.error();
}
return WrapMapper.ok();
}
}