https://blog.csdn.net/xuxiannian/article/details/99625085

Springboot+MyBatis-plus+postgresSQL 的整合

禛陌 2019-08-15 12:20:10  6752  收藏 7

分类专栏: 技术相关 文章标签: Springboot+MyBatis-plus+postgresSQL

版权

磨叨一下

MyBatis-plus 请参看https://mp.baomidou.com/,之前也有写过一个较简单的入门级文章,可以参看
在整合的过程中遇到了一些坑,来扒一扒。
(1) 首先在利用MyBatis-plus-generator 的AutoGenerator类生成代码阶段,死活不生成相应的类。换成MYSQL也是OK的, Oracle也是没有问题。写了一个PostresSQL的直连操作也OK,这说明驱动和连接地址是OK的,问题出在生成过程中。跟入源码,发现在生成时,postgres如果不指定命名空间,会自动加一个命名空间为public。我给数据库分了命名空间,所以,是这个原因,无法找到相应的表,所以一直不能生成相应的类,所以需要给dataSourceConfig.setSchemaName设置指定的命名空间.... 源码在 com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder.getTablesInfo方法中如下图所示:

(2) 整合后又报了个破错:Caused by: java.sql.SQLFeatureNotSupportedException: 这个   org.postgresql.jdbc.PgConnection.createClob() 方法尚未被实作。网上找了一个配制,制完可以解决这个问题
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
(3)  类生成了,但发现生成的相应MAPP无法被扫描到,手动在相应的mapper中加了@Mapper注解,这可累死了,所以去掉注解,直接在springboot启动类中配置@MapperScan(mapper的相应名表)。
(4) 写了个测试用例 ,死活告诉我说表名不存在,实际上是没有加上命名空间,即表名前缀,所以死活报错过不去。接着跟源码吧,看了生成的地方,没有办法在生成mapper时把这个表名前缀加上。那只能想mybaits是如何工作的了。假装么想一下,也应该是把相应的表名和映射的类放在一个类似map的对象中,根据类名的表名之类  ,然后在拼装SQL,即然map生成了,那如何在拼时加上呢。嗯,得去查查springboot整合mybaits的配置,有没有加命名空间的,果然,搜到了加前缀的配制:
mybatis-plus:global-config:db-config:table-prefix: platform
以上是在做整合、生成代码、测试过程中遇到的坑,下面来说说整合过程~~~~~~~~~~~~~~~~~~~~

1.配制POM

      <!--lombok--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.16.16</version></dependency><!--数据库驱动postgresSQL--><dependency><groupId>org.postgresql</groupId><artifactId>postgresql</artifactId><version>42.2.5.jre7</version></dependency><!--mybatis-plus依赖,报了一个spi错,大致查了下,据说是javssist(3.15.0-GA)版本过低的问题,大家不一定会报,可能与我用的包的依赖有关。所以排除了javasist,在后面又加了一个高版本的。--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.1.2</version><exclusions><exclusion><groupId>org.javassist</groupId><artifactId>javassist</artifactId></exclusion></exclusions></dependency><dependency><groupId>org.javassist</groupId><artifactId>javassist</artifactId><version>3.21.0-GA</version></dependency><!--mybaits-plus生成代码的依赖-><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.1.2</version></dependency><!--mybaits-plus-generator生成代码时,会根据模板类生成相就在的类文件,所以模块需要引入的JAR--><dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId></dependency>

2 application.yml配制

# springboot整合postgres连接配制
spring:datasource:url: jdbc:postgresql://192.168.1.84:5432/supervison_platformusername: supervisonpassword: 123driver-class-name: org.postgresql.Driver
#解决整合后报的一个错:<aused by: java.sql.SQLFeatureNotSupportedException: 这个 org.postgresql.jdbc.PgConnection.createClob() 方法尚未被实作。>    jpa:properties:hibernate:jdbc:lob:non_contextual_creation: true
#mybatis-plus整合,加了表前缀的全局配制,加了类中与表中驼峰的映射,不加会查不出数据,因无法做表与类字段映射
mybatis-plus:global-config:db-config:table-prefix: platform.mapper-locations: classpath*:mapper/*Mapper.xmltype-aliases-package: com.zhanglu.test.supervison.api.dao.entityconfiguration:map-underscore-to-camel-case: true

generator生成代码

package com.zhanglu.test.supervison.api.util;import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
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.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;import static com.baomidou.mybatisplus.generator.config.rules.DateType.ONLY_DATE;/*** @author zhanglu* @ClassName: CodeGeneration* @Description: 代码生成器* @date 2019年8月14日 下午2:55:14*/
public class CodeGeneration {public static String scanner(String tip) {/** 查询出当前库所有表信息* SELECT A.tablename, obj_description(relfilenode, 'pg_class') AS comments FROM pg_tables A, pg_class B                   WHERE A.schemaname='platform' AND A.tablename = B.relname*/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 + "!");}/*** @param args* @Title: main* @Description: 生成*/public static void main(String[] args) {AutoGenerator mpg = new AutoGenerator();// 全局配置GlobalConfig gc = new GlobalConfig();final String projectPath = System.getProperty("user.dir") + "/supervison-api";String filePath = projectPath + "/src/main/java";System.out.println("生成文件 的路径为:" + filePath);gc.setOutputDir(filePath);
//        gc.setOutputDir("E://code");
//        gc.setFileOverride(true);
//        gc.setActiveRecord(false);// 不需要ActiveRecord特性的请改为false
//        gc.setEnableCache(false);// XML 二级缓存
//        gc.setBaseResultMap(true);// XML ResultMap
//        gc.setBaseColumnList(false);// XML columListgc.setOpen(false);gc.setDateType(ONLY_DATE);gc.setAuthor("zhanglu_autoGeneration");// 作者// 自定义文件命名,注意 %s 会自动填充表实体属性!
//        gc.setControllerName("%sAction");
//        gc.setServiceName("%sService");
//        gc.setServiceImplName("%sServiceImpl");
//        gc.setMapperName("%sMapper");
//        gc.setXmlName("%sMapper");mpg.setGlobalConfig(gc);// 数据源配置DataSourceConfig dsc = new DataSourceConfig();dsc.setDriverName("org.postgresql.Driver");dsc.setUsername("supervison");dsc.setPassword("123");dsc.setDbType(DbType.POSTGRE_SQL);dsc.setUrl("jdbc:postgresql://10.212.170.84:5432/supervison_platform");dsc.setSchemaName("platform");mpg.setDataSource(dsc);// 包配置final PackageConfig pc = new PackageConfig();
//        pc.setModuleName("");pc.setParent("com.chnenergy.monitoring.supervison.api.dao");//以下生成的类类型的map的KEY值,可以去常量类中ConstVal获得,为了省事,直接写了字符串Map m = new HashMap();m.put("entity_path", gc.getOutputDir() + File.separator + (pc.getParent().replaceAll("\\.", "\\" + File.separator)) + "/entity");m.put("mapper_path", gc.getOutputDir() + File.separator + (pc.getParent().replaceAll("\\.", "\\" + File.separator)) + "/mapper");
//        m.put("service_path",gc.getOutputDir() + File.separator + (pc.getParent().replaceAll("\\.", "\\" + File.separator)) +"/service");
//        m.put("service_impl_path",gc.getOutputDir() + File.separator + (pc.getParent().replaceAll("\\.", "\\" + File.separator)) + "/service/impl");
//        m.put(ConstVal.CONTROLLER_PATH,gc.getOutputDir() + File.separator + (pc.getParent().replaceAll("\\.", "\\" + File.separator)) + "controller");
//                m.put(ConstVal.XML_PATH,gc.getOutputDir() + File.separator + (pc.getParent().replaceAll("\\.", "\\" + File.separator)) + "/xml");pc.setPathInfo(m);// 自定义配置InjectionConfig cfg = new InjectionConfig() {@Overridepublic void initMap() {// to do nothing}};cfg.setFileOutConfigList(null);mpg.setCfg(cfg);mpg.setPackageInfo(pc);// 配置模板TemplateConfig templateConfig = new TemplateConfig();// 配置自定义输出模板//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别// templateConfig.setEntity("templates/entity2.java");// templateConfig.setService();// templateConfig.setController();
//        templateConfig.setXml(TEMPLATE_XML);mpg.setTemplate(templateConfig);// 策略配置StrategyConfig strategy = new StrategyConfig();strategy.setNaming(NamingStrategy.underline_to_camel);strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//        strategy.setTablePrefix("platform");//strategy.setSuperEntityClass("com.baomidou.ant.common.BaseEntity");strategy.setEntityLombokModel(true);strategy.setRestControllerStyle(true);// 写于父类中的公共字段//strategy.setSuperEntityColumns("id");strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
//        strategy.setControllerMappingHyphenStyle(true);
//        strategy.setTablePrefix(pc.getModuleName() + "_");mpg.setStrategy(strategy);mpg.setTemplateEngine(new FreemarkerTemplateEngine());// 执行生成mpg.execute();}}

生成的结构如下所示:


当然,完全可以去掉xml,没啥用,也可以生成实现类和controller类,SQL可以通过JPA方式直接写就行,eg:

@Select("SELECT * FROM ZHANGLU_OFFICIAL_NEWS N WHERE N. ID IN( SELECT G .NEWS_ID FROM ZHANGLU_OFFICIAL_GROUP_INTE G WHERE G . GROUP_ID = #{groupId}) ORDER BY CREATE_DATE")
IPage<ZhangluOfficialNews> selectPageByGroupId(IPage<ZhangluOfficialNews> page, @Param("groupId") String groupId);

上个测试用例跑一下

package com.zhanglu.test.supervison.api.service.impl;import com.zhanglu.test.supervison.api.dao.entity.PhoOrganization;
import com.zhanglu.test.supervison.api.dao.mapper.PhoOrganizationMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;@SpringBootTest
@RunWith(SpringRunner.class)
public class PhoOrganizationServiceImplTest {@Autowiredprivate PhoOrganizationMapper mapper;@Testpublic void query() {PhoOrganization organization = mapper.selectById("ac524ede04b847079cb44c9db4fde14e");System.out.println(organization.getAddress());}}

以上就OK了,大半天遇到的几个小坑。整理下来,希望对大家有点帮助

Springboot+MyBatis-plus+postgresSQL 的整合相关推荐

  1. springboot+mybatis+maven插件逆向工程整合

    springboot+mybatis 第一步: 第二步 这几个文件可以删除掉,不要问为什么! 这是我自己建的一个数据库 建包 将你自己的参数改好 这些应该不用多说 我都给注释了 点他 啥都不要问就给我 ...

  2. mall整合SpringBoot+MyBatis搭建基本骨架

    本文主要讲解mall整合SpringBoot+MyBatis搭建基本骨架,以商品品牌为例实现基本的CRUD操作及通过PageHelper实现分页查询. mysql数据库环境搭建 下载并安装mysql5 ...

  3. 基于 SpringBoot2.0+优雅整合 SpringBoot+Mybatis

    SpringBoot 整合 Mybatis 有两种常用的方式,一种就是我们常见的 xml 的方式 ,还有一种是全注解的方式.我觉得这两者没有谁比谁好,在 SQL 语句不太长的情况下,我觉得全注解的方式 ...

  4. springboot+mybatis+redis整合

    springBoot+mybatis+redis整合,这里搭建一个简单的框架是为了记录怎么使用redis做缓存. 一.构建一个springboot的maven项目,目录结构如下: 二.在pom.xml ...

  5. 【项目实战】 ---- 简单整合SpringBoot + MyBatis + Themyleaf小项目

    简单整合SpringBoot + MyBatis + Themyleaf小项目 一.项目环境搭建① 二.数据库表设计及项目环境② 三.图片验证码功能 四.用户注册功能 五.用户登录功能 六.员工的查询 ...

  6. springboot mybatis easyui 整合的一个小demo

    springboot mybatis easyui 整合的一个小demo 这是最终完成界面 话不多说 开整! 这是项目结构 数据库 表结构和数据库 (有点乱 之前本来是个正经图书表的 = =.) /* ...

  7. springboot+mybatis+dubbo整合

    PS:搭建框架过程在网上查询了比较多的资料,最后自己再综合得到,如有侵权,请联系删除! 最近整合了springboot+mybatis+dubbo的架构,分享给大家!首先Demo目录架构如下: 首先项 ...

  8. Springboot + Mybatis整合的小demo,火车订票系统

    Springboot +Mybatis 的一个订票系统 这学期开了一门软件测试课程,需要做一个系统用于软件测试的学习,就使用目前JavaEE开发中比较火的SpringBoot + Mybatis做了一 ...

  9. springboot+mybatis+SpringSecurity 实现用户角色数据库管理(一)

    本文使用springboot+mybatis+SpringSecurity 实现用户权限数据库管理 实现用户和角色用数据库存储,而资源(url)和权限的对应采用硬编码配置. 也就是角色可以访问的权限通 ...

最新文章

  1. android常见错误与问题
  2. 一年管理成富翁,三年市场路路通,十年技术一场空
  3. OS / Linux / 文件描述符以及 file 结构体
  4. React-事件机制杂记
  5. 脚本自启动oracle,自动启动和关闭Oracle 脚本
  6. 各种一维卷积(Full卷积、Same卷积、Valid卷积、带深度的一维卷积)
  7. CCF201703-1 分蛋糕
  8. linux防火墙安装httpd配置,CentOS7下 Apache的安装配置方法
  9. SpringBoot+Swagger整合API
  10. 开源编译工具和编译软件
  11. wps 项目进度_wps excle做甘特图|如何利用excel自动生成施工进度计划横道图
  12. vue 点击a链接 实现url下载文件
  13. 新版谷歌flash的问题
  14. 平安夜 送自己一个小博客
  15. python+tkinter实现绘图板
  16. 不规则动词分类记忆一览表
  17. 满足于一种廉价的幸福?
  18. 物联网(IOT) 数据库需求和当前技术解析
  19. 计算机术语hpa,hpa(计算机术语)_百度百科
  20. java-把最后一个two单词首字母大写

热门文章

  1. H264学习_基本数据结构
  2. A Simple Math Problem(2020 ICPC 江西省省赛)
  3. 牛客题霸 [三个数的最大乘积]C++题解/答案
  4. Musical Theme pku1743 (后缀数组)
  5. 【每日一题】8月6日题目精讲—追债之旅
  6. AtCoder Regular Contest 061 E - Snuke‘s Subway Trip(建图 + dijkstra最短路 / 0/1bfs / 并查集)
  7. 周末狂欢赛3(跳格子,英雄联盟,排序问题)
  8. AT1219-歴史の研究(历史研究)【回滚莫队】
  9. P4139-上帝与集合的正确用法【欧拉定理】
  10. 【做题记录】 [JLOI2011]不等式组