MyBatis-Plus模板生成🌸[新版]VS[旧版]
遇到的问题
当我们要创建一个新项目时,根据MVC/三层架构的思想,我们要分层开发,需要根据数据库表创建对应的数据访问层、业务实现层、Web访问层(控制层),当然,还需要对应的对应的实体类进行封装。
在国内的话,MyBatis-Plus用的比较多,以User表举例的话,那么在初始话创建的时候:
entity -> User实体类 -> @TableName指定表 @TableId指定主键信息 等
mapper -> UserMapper -> public interface UserMapper extends BaseMapper {}
service -> IUserServer -> public interface IUserService extends IService {}
impl -> UserService ->
@Service public class UserServiceImpl extends ServiceImpl<UserMapper, User>implements IUserService { }
|
controller -> UserController ->
@RestController @RequestMapping("/user") public class UserController {
}
|
创建这些并不是很难,但是,如果表多了,那么创建这些却很繁琐,需要手动创建多个类/接口。
那么,有什么简单一点的方式呢?
新版模板生成器
那么就让我们用一下MyBatis-Plus模板生成器 [新版] 来实现一下吧
官方网站:MyBatis-Plus代码生成器配置-新版
要注意的是,新版的依赖是在3.5.X版本以上,这里使用的是3.5.1,旧版的模板依赖是org.freemarker,而新版使用的是velocity-engine-core的模板引擎,其次是是否需要使用Lombok,如果用的话builder.enableLombok()
开启Lombok
首先引入依赖
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.5.1</version> </dependency>
<dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.0</version> </dependency>
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>
|
接着你需要有几张测试得表:这里我用的是tb_blog
、tb_blog
、tb_shop
、tb_voucher
四张表进行测试
那为了以后回来 康却西
、康却喂
和 修改
,我进行了封装,直接把所有的代码写下来👇👇👇
import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.generator.FastAutoGenerator; import com.baomidou.mybatisplus.generator.config.OutputFile; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.Arrays; import java.util.Collections; import java.util.List;
public class Temp {
private static final String url = "jdbc:mysql://地址:端口/数据库?useSSL=false&serverTimezone=UTC"; private static final String username = "username"; private static final String password = "password";
private static final String AUTHOR_NAME = "Ayaka-icu";
private static final String PACKAGE_NAME = "icu.ayaka"; private static final String DIR_NAME = "/src/main/java"; private static final String MAP_NAME = "/src/main/resources/mapper";
private static final List<String> TBL_NAMES = Arrays.asList("tb_blog","tb_user","tb_shop","tb_voucher");
private static final String TABLE_PREFIX = "tb_";
public static void main(String[] args) { FastAutoGenerator.create(url, username, password) .globalConfig(builder -> { builder.author(AUTHOR_NAME) .outputDir(System.getProperty("user.dir") + DIR_NAME); }) .packageConfig(builder -> { builder .parent(PACKAGE_NAME) .entity("entity") .controller("controller") .mapper("mapper") .service("service") .serviceImpl("service.impl") .pathInfo(Collections.singletonMap(OutputFile.mapperXml, System.getProperty("user.dir") + "/src/main/resources/mapper")); }) .strategyConfig(builder -> { builder.addInclude(TBL_NAMES) .addTablePrefix(TABLE_PREFIX) .entityBuilder() .enableLombok() .enableChainModel() .naming(NamingStrategy.underline_to_camel) .columnNaming(NamingStrategy.underline_to_camel) .idType(IdType.AUTO) .formatFileName("%s") .mapperBuilder() .enableMapperAnnotation() .enableBaseResultMap() .enableBaseColumnList() .formatMapperFileName("%sMapper") .formatXmlFileName("%sMapper") .serviceBuilder() .formatServiceFileName("I%sService") .formatServiceImplFileName("%sServiceImpl") .controllerBuilder() .enableRestStyle(); }).execute();
} }
|
来看一下生成前的目录结构和文件
开始运行
运行结束后,让我们看一下生成的 目录
/接口
/类
👇 目录 / 接口 / 类 👇
让我们看看生成tb_user
相关的接口
/类
那么,来写一段测试代码试试看
@RestController @RequestMapping("/user") public class UserController {
@Autowired private IUserService userService; @GetMapping("{id}") public User getById(@PathVariable("id") Long id){ return userService.getById(id); }
@GetMapping("/list") public List<User> getList(){ return userService.list(); } }
|
访问接口:
OK
旧版模板生成器
官方网站:MyBatis-Plus代码生成器配置-旧版
同样:要注意的是,旧版的依赖是在3.5.X版本以下,这里使用的是3.3.2,旧版的模板依赖是org.freemarker
新版的依赖不同:
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.3.2</version> </dependency>
<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.28</version> <scope>compile</scope> </dependency>
|
同样:那为了以后回来 康却西
、康却喂
和 修改
,我进行了封装,直接把所有的代码写下来👇👇👇
import com.baomidou.mybatisplus.core.toolkit.StringPool; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.InjectionConfig; import com.baomidou.mybatisplus.generator.config.*; import com.baomidou.mybatisplus.generator.config.po.TableInfo; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.*;
public class Temp {
private static final String driver = "com.mysql.cj.jdbc.Driver"; private static final String url = "jdbc:mysql://地址:端口/数据库?useSSL=false&serverTimezone=UTC"; private static final String username = "username"; private static final String password = "password";
private static final String AUTHOR_NAME = "Ayaka-icu";
private static final String PACKAGE_NAME = "icu.ayaka.es"; private static final String DIR_NAME = "/src/main/java"; private static final String MAP_NAME = "/src/main/resources/mapper/";
private static final String TBL_NAMES = "tb_blog,tb_user,tb_voucher,tb_sign"; private static final String TABLE_PREFIX = "tb_";
public static void main(String[] args) {
System.out.println("\n\n开始生成模板...\n\n");
AutoGenerator mpg = new AutoGenerator();
GlobalConfig gc = getGlobalConfig(); mpg.setGlobalConfig(gc);
DataSourceConfig dsc = getDataSourceConfig(); mpg.setDataSource(dsc);
PackageConfig pc = getPackageConfig(); mpg.setPackageInfo(pc);
InjectionConfig cfg = getInjectionConfig(); mpg.setCfg(cfg);
TemplateConfig templateConfig = getTemplateConfig(); mpg.setTemplate(templateConfig); mpg.setTemplateEngine(new FreemarkerTemplateEngine());
StrategyConfig strategy = getStrategyConfig(); mpg.setStrategy(strategy);
mpg.execute(); System.out.println("生成模板结束..."); }
private static GlobalConfig getGlobalConfig() { GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); gc.setOutputDir(projectPath + DIR_NAME); gc.setAuthor(AUTHOR_NAME); gc.setOpen(false); gc.setServiceName("I%s" + ConstVal.SERVICE);
return gc; }
private static DataSourceConfig getDataSourceConfig() { DataSourceConfig dsc = new DataSourceConfig(); dsc.setDriverName(driver); dsc.setUrl(url); dsc.setUsername(username); dsc.setPassword(password); return dsc; }
private static PackageConfig getPackageConfig() { PackageConfig pc = new PackageConfig(); pc.setParent(PACKAGE_NAME); return pc; }
private static InjectionConfig getInjectionConfig() {
String templatePath = "/templates/mapper.xml.ftl"; List<FileOutConfig> focList = new ArrayList<>(); String projectPath = System.getProperty("user.dir"); focList.add(new FileOutConfig(templatePath) { @Override public String outputFile(TableInfo tableInfo) { return projectPath + MAP_NAME + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; } });
InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { } }; cfg.setFileOutConfigList(focList); return cfg; }
private static TemplateConfig getTemplateConfig() { TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setXml(null); return templateConfig; }
private static StrategyConfig getStrategyConfig() { StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); strategy.setEntityLombokModel(false); strategy.setRestControllerStyle(true); strategy.setInclude(TBL_NAMES.split(",")); strategy.setControllerMappingHyphenStyle(true); strategy.setTablePrefix(TABLE_PREFIX); return strategy; } }
|
效果一样。