/**
* mybatis 代碼生成器配置
*/
public class CodeGenerator {
public static void main(String[] args){
AutoGenerator mpg = new AutoGenerator();
//全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("kernel");
gc.setServiceName("%sServiceI");//自定義Service接口生成的文件名
gc.setOpen(false);
gc.setBaseResultMap(true);
gc.setDateType(DateType.ONLY_DATE);
mpg.setGlobalConfig(gc);
//配置數據源
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/數據庫?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("用戶名");
dsc.setPassword("密碼");
mpg.setDataSource(dsc);
//包名配置
PackageConfig pc = new PackageConfig();
// pc.setModuleName(scanner("模塊名"));
pc.setParent("包名").setMapper("mapper");
mpg.setPackageInfo(pc);
//自定義配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do
}
};
//自定義輸出配置
List<FileOutConfig> focList = new ArrayList<>();
//自定義配置會優先輸出
focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定義輸出文件名 , 如果你 Entity 設置了前後綴、此處注意 xml 的名稱會跟着發生變化!!
return projectPath + "/src/main/resources/mappers/"
+ tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
/*
cfg.setFileCreate(new IFileCreate() {
@Override
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
// 判斷自定義文件夾是否需要創建
checkDir("調用默認方法創建的目錄,自定義目錄用");
if (fileType == FileType.MAPPER) {
// 已經生成 mapper 文件判斷存在,不想重新生成返回 false
return !new File(filePath).exists();
}
// 允許生成模板文件
return true;
}
});
*/
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定義輸出模板
//指定自定義模板路徑,注意不要帶上.ftl/.vm, 會根據使用的模板引擎自動識別
// 如果模板引擎是 velocity
// String templatePath = "/templates/mapper.xml.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);
//strategy.setSuperControllerClass("com.example.demo.model.BaseEntity");
strategy.setEntityLombokModel(false);//默認是false
// strategy.setSuperEntityClass("你自己的父類實體,沒有就不用設置!");
//strategy.setRestControllerStyle(true);
//公共父類
// 你自己的父類控制器,沒有就不用設置!
//strategy.setSuperControllerClass("com.example.demo.controller.BaseController");
// 寫於父類中的公共字段
//strategy.setSuperEntityColumns("id");
// strategy.setInclude(scanner("表名,多個英文逗號分割").split(","));
// strategy.setInclude("tb_account");
strategy.setControllerMappingHyphenStyle(true);
// strategy.setTablePrefix("tb_");//設置表前綴
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
/**
* <p>
* 讀取控制檯內容
* </p>
*/
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 + "!");
}
}
Spring Boot Maven:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
Spring MVC Maven:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>latest-version</version>
</dependency>
引入 MyBatis-Plus
之後請不要再次引入 MyBatis
以及 MyBatis-Spring
,以避免因版本差異導致的問題。
Spring Boot 工程配置 MapperScan 註解:
@SpringBootApplication
@MapperScan("com.baomidou.mybatisplus.samples.quickstart.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(QuickStartApplication.class, args);
}
}
Spring MVC 工程配置 MapperScan 註解:
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.baomidou.mybatisplus.samples.quickstart.mapper"/>
</bean>
//調整 SqlSessionFactory 爲 MyBatis-Plus 的 SqlSessionFactory
<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
1.mybatis-plus 特性
- 無侵入
- 依賴少,損耗小
- 防SQL注入
- 通用CRUD
- 多種主鍵策略
- 代碼生成
- 內置分頁插件
4.通用CRUD
繼承 BaseMapper 就可以使用 MP 封裝的CRUD。
5.多種主鍵策略
- IdType.AUTO(自動)
- IdType.INPUT(用戶輸入)
- IdType.ID_WORKER(自動)
- IdType.UUID(自動)
配置方法:主鍵ID加註解 @TableId(value = "ID", type = IdType.AUTO),一般情況下會使用自動增長主鍵。
6.代碼生成
MP 自帶代碼生成工具,可以從Controller層直接生成到mapper層包括實體類。
7.內置分頁插件
Page 內置分頁插件
2.代碼生成器配置
添加依賴
MyBatis-Plus 從 3.0.3
之後移除了代碼生成器與模板引擎的默認依賴,需要手動添加相關依賴:
-
添加 代碼生成器 依賴
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.3.1</version> </dependency>
-
添加 模板引擎 依賴,MyBatis-Plus 支持 Velocity(默認)、Freemarker、Beetl,用戶可以選擇自己熟悉的模板引擎,如果都不滿足您的要求,可以採用自定義模板引擎。
Velocity(默認):
<dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.2</version> </dependency>
Freemarker:
<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.30</version> </dependency>
- 注意!如果您選擇了非默認引擎,需要在 AutoGenerator 中 設置模板引擎。
AutoGenerator generator = new AutoGenerator();
// set freemarker engine
generator.setTemplateEngine(new FreemarkerTemplateEngine());
// set beetl engine
generator.setTemplateEngine(new BeetlTemplateEngine());
// set custom engine (reference class is your custom engine class)
generator.setTemplateEngine(new CustomTemplateEngine());
// other config
...
1.dataSource
- 類型:
DataSourceConfig
- 默認值:
null
數據源配置,通過該配置,指定需要生成代碼的具體數據庫:
DataSourceConfig dataSourceConfig = new DataSourceConfig();
dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/ant?useUnicode=true&useSSL=false&characterEncoding=utf8");
dataSourceConfig.setDriverName("com.mysql.jdbc.Driver");
dataSourceConfig.setUsername("root");
dataSourceConfig.setPassword("password");
2.strategy
- 類型:
StrategyConfig
- 默認值:
null
數據庫表配置,通過該配置,可指定需要生成哪些表或者排除哪些表
3.packageInfo
- 類型:
PackageConfig
- 默認值:
null
包名配置,通過該配置,指定生成代碼的包路徑
4.template
- 類型:
TemplateConfig
- 默認值:
null
模板配置,可自定義代碼生成的模板,實現個性化操作
5.globalConfig
- 類型:
GlobalConfig
- 默認值:
null
全局策略配置:
GlobalConfig globalConfig = new GlobalConfig();
globalConfig.setOutputDir(System.getProperty("user.dir") + "/src/main/java");
globalConfig.setAuthor("jobob");
globalConfig.setOpen(false);
6.injectionConfig
- 類型:
InjectionConfig
- 默認值:
null
注入配置,通過該配置,可注入自定義參數等操作以實現個性化操作
3.自定義模板引擎
請繼承類 com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine
1.自定義代碼模板
//指定自定義模板路徑, 位置:/resources/templates/entity2.java.ftl(或者是.vm)
//注意不要帶上.ftl(或者是.vm), 會根據使用的模板引擎自動識別
TemplateConfig templateConfig = new TemplateConfig()
.setEntity("templates/entity2.java");
AutoGenerator mpg = new AutoGenerator();
//配置自定義模板
mpg.setTemplate(templateConfig);
2.自定義屬性注入
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);
}
};
AutoGenerator mpg = new AutoGenerator();
//配置自定義屬性注入
mpg.setCfg(injectionConfig);
entity2.java.ftl
自定義屬性注入abc=${cfg.abc}
entity2.java.vm
自定義屬性注入abc=$!{cfg.abc}
3.字段其他信息查詢注入
new DataSourceConfig().setDbQuery(new MySqlQuery() {
/**
* 重寫父類預留查詢自定義字段<br>
* 這裏查詢的 SQL 對應父類 tableFieldsSql 的查詢字段,默認不能滿足你的需求請重寫它<br>
* 模板中調用: table.fields 獲取所有字段信息,
* 然後循環字段獲取 field.customMap 從 MAP 中獲取注入字段如下 NULL 或者 PRIVILEGES
*/
@Override
public String[] fieldCustom() {
return new String[]{"NULL", "PRIVILEGES"};
}
})