• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

springboot整合mybatis-plus逆向工程的实现

springboot 搞代码 4年前 (2022-01-05) 17次浏览 已收录 0个评论

这篇文章主要介绍了springboot整合mybatis-plus逆向工程的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。官方文档

代码生成器

AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。

mybatis-plus是根据数据库表来生成对应的实体类,首先我们创建数据库表User

id name age email
1 Jone 18 [email protected]
2 Jack 20 [email protected]
3 Tom 28 [email protected]
4 Sandy 21 [email protected]
5 Billie 24 [email protected]

其对应的数据库 Schema 脚本如下:

 DROP TABLE IF EXISTS user; CREATE TABLE user ( id BIGINT(20) NOT NULL COMMENT '主键ID', name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名', age INT(11) NULL DEFAULT NULL COMMENT '年龄', email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱', PRIMARY KEY (id) );

其对应的数据库 Data 脚本如下:

 DELETE FROM user; INSERT INTO user (id, name, age, email) VALUES (1, 'Jone', 18, '[email protected]'), (2, 'Jack', 20, '[email protected]'), (3, 'Tom', 28, '[email protected]'), (4, 'Sandy', 21, '[email protected]'), (5, 'Billie', 24, '[email protected]');

初始化springboot工程

其中mpconfig就是我们逆向工程配置文件

基本依赖如下:

   org.springframework.bootspring-boot-starter-web org.springframework.bootspring-boot-starter-testtest mysqlmysql-connector-javaruntime org.projectlomboklomboktrue

下面开始引入逆向工程依赖

MyBatis-Plus 从 3.0.3 之后移除了代码生成器与模板引擎的默认依赖,需要手动添加相关依赖:

  com.baomidoumybatis-plus-boot-starter3.1.1<!--添加 代码生成器 依赖--> com.baomidoumybatis-plus-generator3.1.1

添加 模板引擎 依赖,MyBatis-Plus 支持 Velocity(默认)、Freemarker、Beetl,用户可以选择自己熟悉的模板引擎,如果都不满足您的要求,可以采用自定义模板引擎。

Velocity(默认):

  org.apache.velocityvelocity-engine-core2.1

Freemarker:

  org.freemarkerfreemarker2.3.28

这里我选择Freemarker
注意!如果您选择了非默认引擎,需要在 AutoGenerator 中 设置模板引擎

全部依赖如下:

   org.springframework.bootspring-boot-starter-web org.springframework.bootspring-b<em style="color:transparent">来源[email protected]搞@^&代*@码网</em>oot-starter-testtest<!-- freemarker 模板引擎 --> org.freemarkerfreemarker2.3.23 com.baomidoumybatis-plus-boot-starter3.1.1<!--添加 代码生成器 依赖--> com.baomidoumybatis-plus-generator3.1.1 org.projectlomboklomboktrue mysqlmysql-connector-javaruntime

下面开始:创建逆向工程配置类mpconfig

 package com.jiangfeixiang.mpdemo.mpconfig; import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException; import com.baomidou.mybatisplus.core.toolkit.StringPool; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.InjectionConfig; import com.baomidou.mybatisplus.generator.config.*; import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert; 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.*; /** * @ProjectName: mybatis-plus * @Package: com.jiangfeixiang.mybatisplus.mpconfig * @ClassName: CodeGenerator * @Author: jiangfeixiang * @email: [email protected] * @Description: 代码生成器 * @Date: 2019/5/10/0010 21:41 */ public class CodeGenerator { /** * 读取控制台内容 */ 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 globalConfig = new GlobalConfig(); //生成文件的输出目录 String projectPath = System.getProperty("user.dir"); globalConfig.setOutputDir(projectPath + "/src/main/java"); //Author设置作者 globalConfig.setAuthor("姜飞祥"); //是否覆盖文件 globalConfig.setFileOverride(true); //生成后打开文件 globalConfig.setOpen(false); mpg.setGlobalConfig(globalConfig); /** * 数据源配置 */ DataSourceConfig dataSourceConfig = new DataSourceConfig(); // 数据库类型,默认MYSQL dataSourceConfig.setDbType(DbType.MYSQL); //自定义数据类型转换 dataSourceConfig.setTypeConvert(new MySqlTypeConvert()); dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/mp?characterEncoding=utf-8&serverTimezone=GMT%2B8&useSSL=false"); dataSourceConfig.setDriverName("com.mysql.jdbc.Driver"); dataSourceConfig.setUsername("root"); dataSourceConfig.setPassword("1234"); mpg.setDataSource(dataSourceConfig); /** * 包配置 */ PackageConfig pc = new PackageConfig(); pc.setModuleName(scanner("模块名")); //父包名。如果为空,将下面子包名必须写全部, 否则就只需写子包名 pc.setParent("com.jiangfeixiang.mpdemo"); 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 focList = new ArrayList(); // 自定义配置会被优先输出 focList.add(new FileOutConfig(templatePath) { @Override public String outputFile(TableInfo tableInfo) { // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!! return projectPath + "/src/main/resources/mapper/"+ pc.getModuleName() + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; } }); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); /** * 配置模板 */ TemplateConfig templateConfig = new TemplateConfig(); // 配置自定义输出模板 //指定自定义模板路径,注意不要带上.ftl/.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.setInclude(scanner("表名,多个英文逗号分割").split(",")); //实体是否为lombok模型(默认 false) strategy.setEntityLombokModel(true); //生成 @RestController 控制器 strategy.setRestControllerStyle(true); //设置自定义继承的Entity类全称,带包名 //strategy.setSuperEntityClass("com.jiangfeixiang.mpdemo.BaseEntity"); //设置自定义继承的Controller类全称,带包名 //strategy.setSuperControllerClass("com.jiangfeixiang.mpdemo.BaseController"); //设置自定义基础的Entity类,公共字段 strategy.setSuperEntityColumns("id"); //驼峰转连字符 strategy.setControllerMappingHyphenStyle(true); //表名前缀 strategy.setTablePrefix(pc.getModuleName() + "_"); mpg.setStrategy(strategy); mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute(); } } 

拆分详解如下:

 /** * 读取控制台内容 */ 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 + "!"); }

读取控制台内容无需更改,因为稍后启动main方法只会需要在控制台输入模块名以及数据库表名。官网参考
接下来是main方法,这个也是主程序,逆向工程启动方法。下面看一下配置

 AutoGenerator mpg = new AutoGenerator();

代码生成器,所有的配置都需要set进去

全局配置:

 GlobalConfig globalConfig = new GlobalConfig(); //生成文件的输出目录(下面两行无需改动) String projectPath = System.getProperty("user.dir"); globalConfig.setOutputDir(projectPath + "/src/main/java"); //Author设置作者 globalConfig.setAuthor("姜飞祥"); //是否覆盖文件 globalConfig.setFileOverride(true); //生成后打开文件 globalConfig.setOpen(false); //set进去代码生成器对象中 mpg.setGlobalConfig(globalConfig);

数据源配置

 DataSourceConfig dataSourceConfig = new DataSourceConfig(); // 数据库类型,默认MYSQL dataSourceConfig.setDbType(DbType.MYSQL); //自定义数据类型转换 dataSourceConfig.setTypeConvert(new MySqlTypeConvert()); //驱动,URL,用户名以及密码配置,这里使用的是mysql5.6版本 dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/mp?characterEncoding=utf-8&serverTimezone=GMT%2B8&useSSL=false"); dataSourceConfig.setDriverName("com.mysql.jdbc.Driver"); dataSourceConfig.setUsername("root"); dataSourceConfig.setPassword("1234"); //set进去代码生成器对象中 mpg.setDataSource(dataSourceConfig);

包配置

 PackageConfig pc = new PackageConfig(); //这里的模块名需要在控制台输入的,即生成的代码在哪个包下 pc.setModuleName(scanner("模块名")); //父包名。如果为空子包名必须写全部, 否则就只需写子包名 pc.setParent("com.jiangfeixiang.mpdemo"); //set进去代码生成器对象中 mpg.setPackageInfo(pc);

上面父包名是根据工程路径来的,如下参考:

自定义配置

 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { // to do nothing } };

自定义输出配置

 String templatePath = "/templates/mapper.xml.ftl"; List focList = new ArrayList(); // 自定义配置会被优先输出 focList.add(new FileOutConfig(templatePath) { @Override public String outputFile(TableInfo tableInfo) { // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!! return projectPath + "/src/main/resources/mapper/"+ pc.getModuleName() + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; } }); //这块是set到上面自定义配置中 cfg.setFileOutConfigList(focList); //set进去代码生成器对象中 mpg.setCfg(cfg);

最后是策略配置

 StrategyConfig strategy = new StrategyConfig(); //设置命名格式 strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); strategy.setInclude(scanner("表名,多个英文逗号分割").split(",")); //实体是否为lombok模型(默认 false) strategy.setEntityLombokModel(true); //生成 @RestController 控制器 strategy.setRestControllerStyle(true); //设置自定义继承的Entity类全称,带包名 //strategy.setSuperEntityClass("com.jiangfeixiang.mpdemo.BaseEntity"); //设置自定义继承的Controller类全称,带包名 //strategy.setSuperControllerClass("com.jiangfeixiang.mpdemo.BaseController"); //设置自定义基础的Entity类,公共字段 strategy.setSuperEntityColumns("id"); //驼峰转连字符 strategy.setControllerMappingHyphenStyle(true); //表名前缀 strategy.setTablePrefix(pc.getModuleName() + "_"); mpg.setStrategy(strategy); mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute();

以上全部配置好之后直接启动main方法,之后进入控制台

我的模块名是springbootmp,因为我有两张表,输入两个表的名称回车即可生成对应的代码,所生成的代码在模块名springbootmp下

正确执行控制台输出如下

然后看一下模块:

xxxmapper.xml文件是空的:

实体类已经加上@Data注解省略了get/set方法并序列化

mapper接口继承了BaseMapper

接口中没有数据的增删改查方法,那么我们直接在UserController类中注入IUserService接口,查询所有user看看有没有输出:

 @RestController @RequestMapping("/springbootmp/user") public class UserController { @Autowired private IUserService iUserService; /** * 获取所有User * @return */ @RequestMapping("/getAllUser") public List getAllUser(){ List list = iUserService.list(); return list; } }

项目运行直接报错如下:

原因是因为主程序中没有加入@MapperScan(“com.jiangfeixiang.mpdemo.springbootmp.mapper”)

引入即可。之后重新运行启动成功控制台如下图:

还有mybatisplus是不是很漂亮。
调用接口测试如下

源码

到此这篇关于springboot整合mybatis-plus逆向工程的实现的文章就介绍到这了,更多相关springboot mybatis-plus逆向工程内容请搜索gaodaima搞代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持gaodaima搞代码网

以上就是springboot整合mybatis-plus逆向工程的实现的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:springboot整合mybatis-plus逆向工程的实现

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址