Java学习——Spingboot整合Mybatis-Plus
已经很久没写博客了,原因就是懒。这几天搞个springboot项目,刚构建项目就遇到个问题,问题大致描述为springboot和mybatis-plus发生冲突,在原项目中死活得不到解决,怀疑是电脑或是IDEA的问题,因此开了个demo项目来整合试试,结果没问题,百思不得其解,所以烦闷之下写篇博客纪念下。
内容分为以下五个部分:
(一)构建springboot项目
- 打开IDEA,创建项目,选择spring Initializer
可能是校园网问题,时不时会出现连接不上的问题,多试几次直到成功,当然也有可能是以下两个问题:
1、无法连接https://start.spring.io
2、IDEA应用被防火墙禁用
解决方法:
1、试试连接https://start.spring.io
2、到控制面板–>系统和安全–>允许应用通过Windows防火墙–>更改设置
-
选择Developer Tools中的spring Boot DevTools即可,其他的到项目中再进行添加
(二)mybatis-plus 代码生成器
-
打开MyBatis-Plus开发文档https://mp.baomidou.com/guide/generator.html根据教程创建CodeGenerator类和添加相关依赖
-
pom.xml
<!-- web 依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.4.3</version> </dependency> <!-- lombok 依赖--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> <scope>provided</scope> </dependency> <!-- mysql 依赖--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.21</version> </dependency> <!-- mybatis-plus 依赖--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.3.2</version> </dependency> <!-- mybatis-plus-generator 依赖--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.3.2</version> </dependency> <!-- freemark 依赖--> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.31</version> </dependency>
添加以上依赖即可,其实代码生成器只需要最后两个依赖,前面的依赖是为了第三步准备。
-
创建CodeGenerator.java类,我会介绍一下哪些东西需要改
/** 1、首先将mybatis-plus的演示例子复制下来 2、然后将报红的类依次导入 3、具体操作看以下注释 4、没有注释的地方表示不用改 **/ // 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中 public class CodeGenerator { /** * <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.isNotBlank(ipt)) { return ipt; } } throw new MybatisPlusException("请输入正确的" + tip + "!"); } 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("jobob"); gc.setOpen(false); // gc.setSwagger2(true); 实体属性 Swagger2 注解 mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); /** 1、数据源地址,根据自己的数据库进行更改 2、查看自己mysql版本,如有需要改成com.mysql.cj.jdbc.Driver 3、用户名和密码 4、这里以mysql举例,有其他数据库的同理按配置更改 **/ dsc.setUrl("jdbc:mysql://localhost:3306/ant?useUnicode=true&useSSL=false&characterEncoding=utf8"); // dsc.setSchemaName("public"); dsc.setDriverName("com.mysql.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("密码"); mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); /** 这里为代码文件的主要模块,PackageConfig有多种方法,可以自行查看 此处举例: pc.setParent("com.xxx.xxx") //设置包位置,根据自己项目放置模块的位置设置 .setMapper("mapper")//mapper类包名 .setEntity("entity");//实体类,一般我们只需要这两个包 也可以按照官方示例在控制台输入想要生成的模块。 **/ //pc.setModuleName(scanner("模块名")); //pc.setParent("com.baomidou.ant"); mpg.setPackageInfo(pc); // 自定义配置 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { // to do nothing } }; // 如果模板引擎是 freemarker,这里我们用的是freemark String templatePath = "/templates/mapper.xml.ftl"; // 如果模板引擎是 velocity // String templatePath = "/templates/mapper.xml.vm"; // 自定义输出配置 List<FileOutConfig> focList = new ArrayList<>(); // 自定义配置会被优先输出 focList.add(new FileOutConfig(templatePath) { @Override public String outputFile(TableInfo tableInfo) { // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!! //生成resources文件中的mapper.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() templateConfig.setXml(null); mpg.setTemplate(templateConfig); // 策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); //strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!"); strategy.setEntityLombokModel(true); strategy.setRestControllerStyle(true); // 公共父类 //strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!"); // 写于父类中的公共字段 strategy.setSuperEntityColumns("id"); strategy.setInclude(scanner("表名,多个英文逗号分割").split(",")); strategy.setControllerMappingHyphenStyle(true); //"_"表示表名的前缀,比如你的表都是sys_开头(如sys_admin,sys_role等等),那就改成"sys_" strategy.setTablePrefix(pc.getModuleName() + "_"); mpg.setStrategy(strategy); mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute(); } }
-
然后启动,在控制台输入对应数据库的表名(全名),回车即可等待生成代码文件
(三)整合
-
application.yml
server: port: 8081 spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver data-username: root data-password: 123456 url: jdbc:mysql://localhost:3306/datasourcename?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC
配置数据源,同代码生成器连接的数据库
-
xxxApplication.java项目的启动文件,添加扫描mapper文件的注解
@SpringBootApplication @MapperScan("com.thesis.oer.mapper") public class xxxApplication { public static void main(String[] args) { SpringApplication.run(OerApplication.class, args); } }
其实整合到这里基本就结束了,启动项目看是否成功,如果成功了,那你就可以使用mybatis-plus去实现业务逻辑了。
(四)我遇到的问题
-
报错“Failed to configure a DataSource: ‘url’ attribute is not specified and no embedded datasource could be configured.”
看到一篇文章讲的比较好,报这种错的原因除了IDEA给的两个提示之外,可以从以下方面去寻找报错原因:
-
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
这种方法是阻止springboot自动配置,采用这种解决方法一般是多数据源的情况,需要自己另外手动配置数据源,手动配置的方式比较复杂,自行百度。我自己并不像采用这种方式,一来是手动配置过于麻烦,二是本来就有更好的解决方法。这个方法一般用户客户端(指不需要用到数据源)。
-
没有配置spring.datasource.url
-
spring.datasource.url格式有问题
假如你按照我的教程来,那就不会是上面这两个原因的。spring.datasource.url的格式问题稍稍注意一下都不会有问题(严格控制缩进),假如你害怕application.yml文件容易出错,那么可以用application.properties文件,效果也是一样,相对来说properties格式更加不容易出错,yml更加直观。
-
配置 spring.datasource.url的文件没有加载
打开File–>Projec Structure,如图查看项目的配置文件,如果没有显示证明配置文件没有加载,那就百度寻找一下解决方法。
-
(五)总结
假如你是对照我的教程查看项目的配置没有问题还是报错了,那就证明出现了某种不可名状的错误,如同我被卡了一天的项目一般,我只能忍痛删掉项目,换了个路径重新建,还好也只是刚搭好框架而已,但是一天时间就浪费了,还伴随着憋屈的心情写下了这篇文章。