一、前言
二、配置
com.baomidou
mybatis-plus-boot-starter
3.1.0
com.baomidou
mybatis-plus-generator
3.1.0
org.apache.velocity
velocity-engine-core
2.1
org.apache.commons
commons-lang3
com.alibaba
druid-spring-boot-starter
1.1.20
com.baomidou
dynamic-datasource-spring-boot-starter
2.5.7
org.springframework.boot
spring-boot-starter-actuator
## pojo所在包,使用该注解,在mapper.xml中将不必使用pojo全名-替换
mybatis-plus.type-aliases-package=com.exam.fast.data.dao.po
## mapper.xml所在路径-替换
mybatis-plus.mapper-locations=classpath*:/mapper/**/*Mapper.xml
mybatis-plus.config-location=classpath:myBatis-config.xml
/**
* @desc: mybatis plus分页插件
* @author: yanfei
* @date: 2019/10/28
*/
@EnableTransactionManagement
@Configuration
@MapperScan("com.exam.fast.data.dao.mapper")
public class MybatisPlusConfig {
/**
* 逻辑删除配置
* @return
*/
@Bean
public ISqlInjector sqlInjector() {
return new LogicSqlInjector();
}
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求 默认false
// paginationInterceptor.setOverflow(false);
// 设置最大单页限制数量,默认 500 条,-1 不受限制
// paginationInterceptor.setLimit(500);
List sqlParserList = new ArrayList<>();
// 攻击 SQL 阻断解析器、加入解析链
sqlParserList.add(new BlockAttackSqlParser() {
@Override
public void processDelete(Delete delete) {
// 如果你想自定义做点什么,可以重写父类方法像这样子
// 自定义跳过某个表,其他关联表可以调用 delete.getTables() 判断
super.processDelete(delete);
}
});
paginationInterceptor.setSqlParserList(sqlParserList);
return paginationInterceptor;
}
}
三、自动生成
#非mapper xml文件生成路径
outputDir=F:/demoSpace/dynamic-boot/src/main/java
#mapper xml文件生成路径
outputXmlDir=F:/demoSpace/dynamic-boot/src/main/resources
#父包名路径;
package.parent=com.exam.fast
#数据库配置
ds.driver-class-name=com.mysql.jdbc.Driver
ds.username=root
ds.password=yanfei010203
ds.url=jdbc:mysql://192.168.11.138:3306/test?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
/**
* @desc: 执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
* @author: yanfei
* @date: 2019/10/25
*/
public class CodeGenerator {
public static void main(String[] args) {
codeGenerator();
}
/**
*
* 读取控制台内容
*
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
/**
* 生成代码配置
*/
public static void codeGenerator() {
String javaPath = PropKit.use("generator-config.properties").get("outputDir");
String xmlPath = PropKit.use("generator-config.properties").get("outputXmlDir");
String parentPath = PropKit.use("generator-config.properties").get("package.parent");
String driverName = PropKit.use("generator-config.properties").get("ds.driver-class-name");
String username = PropKit.use("generator-config.properties").get("ds.username");
String password = PropKit.use("generator-config.properties").get("ds.password");
String url = PropKit.use("generator-config.properties").get("ds.url");
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir(javaPath);
gc.setAuthor("yanfei");
gc.setOpen(false);
// gc.setSwagger2(true); //实体属性 Swagger2 注解
//例如:%sBusiness 生成 UserBusiness
gc.setServiceName("I%sManager");
//例如:%sBusinessImpl 生成 UserBusinessImpl
gc.setServiceImplName("%sManagerImpl");
gc.setBaseColumnList(true);
gc.setBaseResultMap(true);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl(url);
// dsc.setSchemaName("public");
dsc.setDriverName(driverName);
dsc.setUsername(username);
dsc.setPassword(password);
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(scanner("模块名"));
pc.setParent(parentPath);
pc.setService("manager");
pc.setServiceImpl("manager.impl");
pc.setEntity("po");
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
// String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
String templatePath = "/templates/mapper.xml.vm";
// 自定义输出配置
List focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return xmlPath + "/mapper/" + pc.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
/*
cfg.setFileCreate(new IFileCreate() {
@Override
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
// 判断自定义文件夹是否需要创建
checkDir("调用默认方法创建的目录");
return false;
}
});
*/
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板(默认自带模板)
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
// templateConfig.setEntity("templates/entity2.java");
// templateConfig.setService();
// templateConfig.setController();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//自定义基础的Entity类
// strategy.setSuperEntityClass("com.exam.business.middle.fastboot.common.BaseEntity");
//是否为lombok模型
strategy.setEntityLombokModel(true);
//生成 @RestController 控制器
strategy.setRestControllerStyle(true);
//自定义继承的Controller类全称,带包名
// strategy.setSuperControllerClass("com.exam.business.middle.fastboot.common.BaseController");
// 写于父类中的公共字段
// strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
//驼峰转连字符
strategy.setControllerMappingHyphenStyle(true);
//是否生成实体时,生成字段注解
// strategy.setEntityTableFieldAnnotationEnable(true);
// strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new VelocityTemplateEngine());
mpg.execute();
}
}
/**
* desc:获取文件工具类,可以在任何地方使用PropKit.Use("aa.txt").get("key")
* @author:yanfei
* date:2018/6/13
*/
public class PropKit {
private static Prop prop = null;
private static final ConcurrentHashMap map = new ConcurrentHashMap();
private PropKit() {
}
/**
* Using the properties file. It will loading the properties file if not loading.
*
* @see #use(String, String)
*/
public static Prop use(String fileName) {
return use(fileName, Prop.DEFAULT_ENCODING);
}
/**
* Using the properties file. It will loading the properties file if not loading.
*
* Example:
* PropKit.use("config.txt", "UTF-8");
* PropKit.use("other_config.txt", "UTF-8");
*
* String userName = PropKit.get("userName");
* String password = PropKit.get("password");
*
* userName = PropKit.use("other_config.txt").get("userName");
* password = PropKit.use("other_config.txt").get("password");
*
* PropKit.use("com/cc/config_in_sub_directory_of_classpath.txt");
*
* @param fileName the properties file's name in classpath or the sub directory of classpath
* @param encoding the encoding
*/
public static Prop use(String fileName, String encoding) {
Prop result = map.get(fileName);
if (result == null) {
result = new Prop(fileName, encoding);
map.put(fileName, result);
if (PropKit.prop == null) {
PropKit.prop = result;
}
}
return result;
}
/**
* Using the properties file bye File object. It will loading the properties file if not
* loading.
*
* @see #use(File, String)
*/
public static Prop use(File file) {
return use(file, Prop.DEFAULT_ENCODING);
}
/**
* Using the properties file bye File object. It will loading the properties file if not
* loading.
*
* Example:
* PropKit.use(new File("/var/config/my_config.txt"), "UTF-8");
* Strig userName = PropKit.use("my_config.txt").get("userName");
*
* @param file the properties File object
* @param encoding the encoding
*/
public static Prop use(File file, String encoding) {
Prop result = map.get(file.getName());
if (result == null) {
result = new Prop(file, encoding);
map.put(file.getName(), result);
if (PropKit.prop == null) {
PropKit.prop = result;
}
}
return result;
}
public static Prop useless(String fileName) {
Prop previous = map.remove(fileName);
if (PropKit.prop == previous) {
PropKit.prop = null;
}
return previous;
}
public static void clear() {
prop = null;
map.clear();
}
public static Prop getProp() {
if (prop == null) {
throw new IllegalStateException(
"Load propties file by invoking PropKit.use(String fileName) method first.");
}
return prop;
}
public static Prop getProp(String fileName) {
return map.get(fileName);
}
public static String get(String key) {
return getProp().get(key);
}
public static String get(String key, String defaultValue) {
return getProp().get(key, defaultValue);
}
public static Integer getInt(String key) {
return getProp().getInt(key);
}
public static Integer getInt(String key, Integer defaultValue) {
return getProp().getInt(key, defaultValue);
}
public static Long getLong(String key) {
return getProp().getLong(key);
}
public static Long getLong(String key, Long defaultValue) {
return getProp().getLong(key, defaultValue);
}
public static Boolean getBoolean(String key) {
return getProp().getBoolean(key);
}
public static Boolean getBoolean(String key, Boolean defaultValue) {
return getProp().getBoolean(key, defaultValue);
}
public static boolean containsKey(String key) {
return getProp().containsKey(key);
}
}
/**
* @desc:Prop can load properties file from CLASSPATH or File object
* @author:yanfei
* @date:2018/6/13
*/
public class Prop {
private Properties properties = null;
public static String DEFAULT_ENCODING = "UTF-8";
/**
* Prop constructor.
* @author Administrator
* @see #Prop(String, String)
*/
public Prop(String fileName) {
this(fileName, DEFAULT_ENCODING);
}
/**
* Prop constructor
*
* Example:
* Prop prop = new Prop("my_config.txt", "UTF-8");
* String userName = prop.get("userName");
*
* prop = new Prop("com/file_in_sub_path_of_classpath.txt", "UTF-8");
* String value = prop.get("key");
*
* @param fileName the properties file's name in classpath or the sub directory of classpath
* @param encoding the encoding
*/
public Prop(String fileName, String encoding) {
InputStream inputStream = null;
try {
// properties.load(Prop.class.getResourceAsStream(fileName));
inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
if (inputStream == null) {
throw new IllegalArgumentException("Properties file not found in classpath: " + fileName);
}
properties = new Properties();
properties.load(new InputStreamReader(inputStream, encoding));
} catch (IOException e) {
throw new RuntimeException("Error loading properties file.", e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.getMessage();
}
}
}
}
/**
* Prop constructor.
*
* @see #Prop(File, String)
*/
public Prop(File file) {
this(file, DEFAULT_ENCODING);
}
/**
* Prop constructor
*
* Example:
* Prop prop = new Prop(new File("/var/config/my_config.txt"), "UTF-8");
* String userName = prop.get("userName");
*
* @param file the properties File object
* @param encoding the encoding
*/
public Prop(File file, String encoding) {
if (file == null) {
throw new IllegalArgumentException("File can not be null.");
}
if (file.isFile() == false) {
throw new IllegalArgumentException("File not found : " + file.getName());
}
InputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
properties = new Properties();
properties.load(new InputStreamReader(inputStream, encoding));
} catch (IOException e) {
throw new RuntimeException("Error loading properties file.", e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.getMessage();
}
}
}
}
public String get(String key) {
return properties.getProperty(key);
}
public String get(String key, String defaultValue) {
return properties.getProperty(key, defaultValue);
}
public Integer getInt(String key) {
return getInt(key, null);
}
public Integer getInt(String key, Integer defaultValue) {
String value = properties.getProperty(key);
if (value != null) {
return Integer.parseInt(value.trim());
}
return defaultValue;
}
public Long getLong(String key) {
return getLong(key, null);
}
public Long getLong(String key, Long defaultValue) {
String value = properties.getProperty(key);
if (value != null) {
return Long.parseLong(value.trim());
}
return defaultValue;
}
public Boolean getBoolean(String key) {
return getBoolean(key, null);
}
public Boolean getBoolean(String key, Boolean defaultValue) {
String value = properties.getProperty(key);
if (value != null) {
value = value.toLowerCase().trim();
if ("true".equals(value)) {
return true;
} else if ("false".equals(value)) {
return false;
}
throw new RuntimeException("The value can not parse to Boolean : " + value);
}
return defaultValue;
}
public boolean containsKey(String key) {
return properties.containsKey(key);
}
public Properties getProperties() {
return properties;
}
}
四、续