一、为什么要使用MybatisPlusGenerator?
在上篇中讲到使用Spring Boot引入了mabytis,通过把sql语句写在xml配置文件中操作数据库。那么设想现在要操作多张表,用原来的办法是不是需要手动创建N个类,手写N条sql语句,手不累,心也累。于是乎MybatisPlusGenerator应运而生
二、实现过程
2.1、创建MybatisPlusGenerator类
这里已经帮你写好了,你可以直接拿来用
/**
* MyBatisPlus代码生成器
* Created by huice on 2021/7/6.
*/publicclassMyBatisPlusGenerator{publicstaticvoidmain(String[] args){
String projectPath= System.getProperty("user.dir");
String moduleName=scanner("模块名");
String[] tableNames=scanner("表名,多个英文逗号分割").split(",");// 代码生成器
AutoGenerator autoGenerator=newAutoGenerator();
autoGenerator.setGlobalConfig(initGlobalConfig(projectPath));
autoGenerator.setDataSource(initDataSourceConfig());
autoGenerator.setPackageInfo(initPackageConfig(moduleName));
autoGenerator.setCfg(initInjectionConfig(projectPath, moduleName));
autoGenerator.setTemplate(initTemplateConfig());
autoGenerator.setStrategy(initStrategyConfig(tableNames));
autoGenerator.setTemplateEngine(newVelocityTemplateEngine());
autoGenerator.execute();}/**
* 读取控制台内容信息
*/privatestatic Stringscanner(String tip){
Scanner scanner=newScanner(System.in);
System.out.println(("请输入"+ tip+":"));if(scanner.hasNext()){
String next= scanner.next();if(StrUtil.isNotEmpty(next)){return next;}}thrownewMybatisPlusException("请输入正确的"+ tip+"!");}/**
* 初始化全局配置
*/privatestatic GlobalConfiginitGlobalConfig(String projectPath){
GlobalConfig globalConfig=newGlobalConfig();
globalConfig.setOutputDir(projectPath+"/src/main/java");
globalConfig.setAuthor("smy");
globalConfig.setOpen(false);
globalConfig.setSwagger2(true);
globalConfig.setBaseResultMap(true);
globalConfig.setFileOverride(true);
globalConfig.setDateType(DateType.ONLY_DATE);
globalConfig.setEntityName("%s");
globalConfig.setMapperName("%sMapper");
globalConfig.setXmlName("%sMapper");
globalConfig.setServiceName("%sService");
globalConfig.setServiceImplName("%sServiceImpl");
globalConfig.setControllerName("%sController");return globalConfig;}/**
* 初始化数据源配置
*/privatestatic DataSourceConfiginitDataSourceConfig(){
Props props=newProps("generator.properties");
DataSourceConfig dataSourceConfig=newDataSourceConfig();
dataSourceConfig.setUrl(props.getStr("dataSource.url"));
dataSourceConfig.setDriverName(props.getStr("dataSource.driverName"));
dataSourceConfig.setUsername(props.getStr("dataSource.username"));
dataSourceConfig.setPassword(props.getStr("dataSource.password"));return dataSourceConfig;}/**
* 初始化包配置
*/privatestatic PackageConfiginitPackageConfig(String moduleName){
Props props=newProps("generator.properties");
PackageConfig packageConfig=newPackageConfig();
packageConfig.setModuleName(moduleName);
packageConfig.setParent(props.getStr("package.base"));
packageConfig.setEntity("model");return packageConfig;}/**
* 初始化模板配置
*/privatestatic TemplateConfiginitTemplateConfig(){
TemplateConfig templateConfig=newTemplateConfig();//可以对controller、service、entity模板进行配置//mapper.xml模板需单独配置
templateConfig.setXml(null);return templateConfig;}/**
* 初始化策略配置
*/privatestatic StrategyConfiginitStrategyConfig(String[] tableNames){
StrategyConfig strategyConfig=newStrategyConfig();
strategyConfig.setNaming(NamingStrategy.underline_to_camel);
strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);
strategyConfig.setEntityLombokModel(true);
strategyConfig.setRestControllerStyle(true);//当表名中带*号时可以启用通配符模式if(tableNames.length==1&& tableNames[0].contains("*")){
String[] likeStr= tableNames[0].split("_");
String likePrefix= likeStr[0]+"_";
strategyConfig.setLikeTable(newLikeTable(likePrefix));}else{
strategyConfig.setInclude(tableNames);}return strategyConfig;}/**
* 初始化自定义配置
*/privatestatic InjectionConfiginitInjectionConfig(String projectPath, String moduleName){// 自定义配置
InjectionConfig injectionConfig=newInjectionConfig(){@OverridepublicvoidinitMap(){// 可用于自定义属性}};// 模板引擎是Velocity
String templatePath="/templates/mapper.xml.vm";// 自定义输出配置
List<FileOutConfig> focList=newArrayList<>();// 自定义配置会被优先输出
focList.add(newFileOutConfig(templatePath){@Overridepublic StringoutputFile(TableInfo tableInfo){// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!return projectPath+"/src/main/resources/mapper/"+ moduleName+"/"+ tableInfo.getEntityName()+"Mapper"+ StringPool.DOT_XML;}});
injectionConfig.setFileOutConfigList(focList);return injectionConfig;}}
2.2、创建generator.properties配置文件
一些连接数据库的配置
dataSource.url=jdbc:mysql://localhost:3306/shengtst?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
dataSource.driverName=com.mysql.cj.jdbc.Driver
dataSource.username=root
dataSource.password=123456package.base=com.smy.myplus.modules
2.3、运行MybatisPlusGenerator文件
输入存放的模块名和你要连接的表名,自动帮你创建moudules.myplus下的所有文件
2.4、在对应表名的controller中,手写你要操作数据库的代码
@RestController@RequestMapping("/myplus/users")publicclassUsersController{@Autowiredprivate UsersService usersService;@GetMapping("/name")public UsersGetUsersByName(@RequestParam("name") String name){
QueryWrapper queryWrapperName=newQueryWrapper();
queryWrapperName.eq("name",name);return usersService.getOne(queryWrapperName);}}
2.5、运行Application启动文件
填个小坑,运行前记得加@MapperScan
@MapperScan("com.smy.myplus.modules.myplus.mapper")@SpringBootApplicationpublicclassMyplusApplication{publicstaticvoidmain(String[] args){
SpringApplication.run(MyplusApplication.class, args);}}
2.6、使用postman调用接口
根据姓名查询,有正常返回
2.6、回顾总结
可以看到真正手写的代码不超过10行,即实现了操作数据库,而且后续其他的sql语句也可以直接调用,嗯真香