/**
* 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"};
}
})