SpringBoot+MybatisPlus+代碼生成器——代碼自動生成
- 1 pom依賴
- 2 項目配置檔案Application.yml——常用配置
- 3 配置檔案——config包下
-
- 3.1 mybatis-plus配置
- 3.2 資料源配置
- 4 代碼生成——代碼生成器Genenator.java
1 pom依賴
<!-- mybatis的orm插件 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatisplus-spring-boot-starter</artifactId>
<version>1.0.4</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>2.0.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.velocity/velocity -->
<!-- 模闆引擎 -->
<!-- velocity模闆 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
<!-- freemarker模闆 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
<!-- thymeleaf模闆 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--資料庫連接配接jdbc依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--mysql連結依賴-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--阿裡druid資料庫連接配接池依賴-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<!--lombok是一個編譯級别的插件,它可以在項目編譯的時候生成一些代碼!-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>0.10.1</version>
<scope>provided</scope>
</dependency>
所有的版本可以去官網檢視最新版
2 項目配置檔案Application.yml——常用配置
server:
port: 8080
spring:
datasource:
name: myBlog
url: jdbc:mysql://localhost:3306/my-blog-info?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&useSSL=false
username: root
password: 123456
type: com.alibaba.druid.pool.DruidDataSource
#MySQL8.0以後版本的驅動
driver-class-name: com.mysql.cj.jdbc.Driver
#配置資料庫連接配接池
druid:
initialSize: 1
minIdle: 1
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: false
maxOpenPreparedStatements: 20
#開啟StatFilter
filter:
stat:
enabled: true
log-slow-sql: true
slow-sql-millis: 1000
#開啟Slf4jFilter
slf4j:
enabled: true
data-source-log-enabled: false
connection-log-enabled: false
statement-log-enabled: false
result-set-log-enabled: false
#開啟WallFilter
wall:
enabled: true
log-violation: true
throw-exception: false
config:
delete-where-none-check: true
#開啟Web監控
web-stat-filter:
enabled: true
exclusions: /druid/*,*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico
url-pattern: /*
#開啟監控頁面
stat-view-servlet:
enabled: true
login-username: admin
login-password: z1320291471
#模闆引擎配置
thymeleaf:
cache: false
mode: LEGACYHTML5
encoding: UTF-8
servlet:
content-type: text/html
#mybatis-plus配置
mybatis-plus:
type-aliases-package: com.site.blog.entity
mapper-locations: classpath*:mapper/*.xml
global-config:
db-config:
table-prefix: "tb_"
#日志配置
logging:
level.com.site.blog: debug
通常會有多個配置檔案——多個開發環境
#預設啟用開發環境配置
spring.profiles.active=dev
#啟用生産環境配置
#spring.profiles.active=pro
3 配置檔案——config包下
3.1 mybatis-plus配置
@Configuration
//掃描dao或者是Mapper接口
@MapperScan("com.warrior.mapper*")
public class MybatisPlusConfig {
/**
* mybatis-plus 分頁插件
*/
@Bean
public PaginationInterceptor paginationInterceptor(){
PaginationInterceptor page = new PaginationInterceptor();
page.setDialectType("mysql");
return page;
}
}
3.2 資料源配置
/**
* 資料源配置
*/
@Configuration
public class DataSourceConfig {
@Bean(name="dataSource")
@ConfigurationProperties(prefix="spring.datasource")
public DataSource dataSource(){
return new DruidDataSource();
}
// 配置事物管理器
@Bean(name="transactionManager")
public DataSourceTransactionManager transactionManager(){
return new DataSourceTransactionManager(dataSource());
}
}
類中所需的包通過編譯器自行導入就OK
4 代碼生成——代碼生成器Genenator.java
通常放在test/java包下運作
/**
* <p>
* 代碼生成器
* </p>
*/
public class Generator {
//代碼輸出路徑
final static String dirPath = "D://";
/**
* <p>
* MySQL 資料庫表-代碼自動生成
* </p>
*/
public static void main(String[] args) {
AutoGenerator mpg = new AutoGenerator();
// 選擇 freemarker 引擎,預設 Veloctiy
//mpg.setTemplateEngine(new FreemarkerTemplateEngine());
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir(dirPath);
gc.setAuthor("lqh");
gc.setFileOverride(true); //是否覆寫
gc.setActiveRecord(true);// 不需要ActiveRecord特性的請改為false
gc.setEnableCache(false);// XML 二級緩存
gc.setBaseResultMap(true);// XML ResultMap
gc.setBaseColumnList(true);// XML columList
// 自定義檔案命名,注意 %s 會自動填充表實體屬性!
// gc.setMapperName("%sDao");
// gc.setXmlName("%sMapper");
// gc.setServiceName("MP%sService");
// gc.setServiceImplName("%sServiceDiy");
// gc.setControllerName("%sAction");
mpg.setGlobalConfig(gc);
// 資料源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL);
dsc.setTypeConvert(new MySqlTypeConvert(){
// 自定義資料庫表字段類型轉換【可選】
@Override
public DbColumnType processTypeConvert(String fieldType) {
System.out.println("轉換類型:" + fieldType);
// 注意!!processTypeConvert 存在預設類型轉換,如果不是你要的效果請自定義傳回、非如下直接傳回。
return super.processTypeConvert(fieldType);
}
});
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
dsc.setUrl("jdbc:mysql://localhost:3306/my-blog-info?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&useSSL=false");
mpg.setDataSource(dsc);
// 政策配置
StrategyConfig strategy = new StrategyConfig();
// strategy.setCapitalMode(true);// 全局大寫命名 ORACLE 注意
strategy.setTablePrefix(new String[] { "tb_", "tsys_" });// 此處可以修改為您的表字首
strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成政策
// strategy.setInclude(new String[] { "user" }); // 需要生成的表
// strategy.setExclude(new String[]{"test"}); // 排除生成的表
// 自定義實體父類
// strategy.setSuperEntityClass("com.baomidou.demo.TestEntity");
// 自定義實體,公共字段
// strategy.setSuperEntityColumns(new String[] { "test_id", "age" });
// 自定義 mapper 父類
// strategy.setSuperMapperClass("com.baomidou.demo.TestMapper");
// 自定義 service 父類
// strategy.setSuperServiceClass("com.baomidou.demo.TestService");
// 自定義 service 實作類父類
// strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl");
// 自定義 controller 父類
// strategy.setSuperControllerClass("com.baomidou.demo.TestController");
// 【實體】是否生成字段常量(預設 false)
// public static final String ID = "test_id";
// strategy.setEntityColumnConstant(true);
// 【實體】是否為建構者模型(預設 false)
// public User setName(String name) {this.name = name; return this;}
strategy.setEntityBuilderModel(true);
mpg.setStrategy(strategy);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com");
pc.setModuleName("blog");
pc.setController("controler");
pc.setEntity("entity");
pc.setMapper("mapper");
pc.setService("service");
pc.setServiceImpl("serviceImpl");
pc.setXml("mapperXml");
mpg.setPackageInfo(pc);
// 注入自定義配置,可以在 VM 中使用 cfg.abc 【可無】
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
this.setMap(map);
}
};
// 自定義 xxList.jsp 生成
List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
/* focList.add(new FileOutConfig("/template/list.jsp.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定義輸入檔案名稱
return "D://my_" + tableInfo.getEntityName() + ".jsp";
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);*/
// 調整 xml 生成目錄示範
/* focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return dirPath + tableInfo.getEntityName() + "Mapper.xml";
}
});
cfg.setFileOutConfigList(focList);
*/
mpg.setCfg(cfg);
// 關閉預設 xml 生成,調整生成 至 根目錄
/* TemplateConfig tc = new TemplateConfig();
tc.setXml(null);
mpg.setTemplate(tc);*/
// 自定義模闆配置,可以 copy 源碼 mybatis-plus/src/main/resources/templates 下面内容修改,
// 放置自己項目的 src/main/resources/templates 目錄下, 預設名稱一下可以不配置,也可以自定義模闆名稱
// TemplateConfig tc = new TemplateConfig();
// tc.setController("...");
// tc.setEntity("...");
// tc.setMapper("...");
// tc.setXml("...");
// tc.setService("...");
// tc.setServiceImpl("...");
// 如上任何一個子產品如果設定 空 OR Null 将不生成該子產品。
// mpg.setTemplate(tc);
// 執行生成
mpg.execute();
// 列印注入設定【可無】
System.err.println(mpg.getCfg().getMap().get("abc"));
}
}
根據自己需求修改Genenator.java檔案就OK