[Spring Boot]整合MyBatis Plus
- 2020 年 9 月 16 日
- 筆記
- Spring Boot
第一步:導入jar包
pom中導入mybatis plus的jar包,因為後面會涉及到程式碼生成,所以我們還需要導入頁面模板引擎,這裡我們用的是freemarker。
<!--mp-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--mp程式碼生成器-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.2.0</version>
</dependency>
第二步:然後去寫配置文件
# DataSource Config
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/vueblog?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai
username: root
password: loveu0222
mybatis-plus:
mapper-locations: classpath*:/mapper/**Mapper.xml
上面除了配置資料庫的資訊,還配置了myabtis plus的mapper的xml文件的掃描路徑,這一步不要忘記了。 第三步:開啟mapper介面掃描,添加分頁插件
新建一個包:通過@mapperScan註解指定要變成實現類的介面所在的包,然後包下面的所有介面在編譯之後都會生成相應的實現類。PaginationInterceptor是一個分頁插件。
com.qiuhuashan.config.MybatisPlusConfig
@Configuration
@EnableTransactionManagement
@MapperScan("com.qiuhuashan.mapper")
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
return paginationInterceptor;
}
}
第四步:程式碼生成
現在就已經可以使用mybatis plus了,官方給我們提供了一個程式碼生成器,然後我寫上自己的參數之後,就可以直接根據資料庫表資訊生成entity、service、mapper等介面和實現類。
package com.qiuhuashan;
// 演示例子,執行 main 方法控制台輸入模組表名回車自動生成對應項目目錄中
public class CodeGenerator {
/**
* <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 + "!");
}
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.setOutputDir("D:\\test");
gc.setAuthor("秋畫扇");
gc.setOpen(false);
// gc.setSwagger2(true); 實體屬性 Swagger2 註解
gc.setServiceName("%sService");
mpg.setGlobalConfig(gc);
// 數據源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/vueblog?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("loveu0222");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(null);
pc.setParent("com.qiuhuashan");
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<FileOutConfig> focList = new ArrayList<>();
// 自定義配置會被優先輸出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定義輸出文件名 , 如果你 Entity 設置了前後綴、此處注意 xml 的名稱會跟著發生變化!!
return projectPath + "/src/main/resources/mapper/"
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
strategy.setInclude(scanner("表名,多個英文逗號分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix("m_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
資料庫表
配置好MyBatis Plus環境之後,使用方法如下圖:
運行CodeGenerator的main方法,在控制台中輸入表名:m_user:
輸入表名提交之後,就可以直接根據資料庫表資訊生成entity、service、mapper等介面和實現類,如下圖