当前位置: 移动技术网 > IT编程>开发语言>Java > Mybatis迁移到Mybatis-Plus的实现方法

Mybatis迁移到Mybatis-Plus的实现方法

2020年08月29日  | 移动技术网IT编程  | 我要评论
由于原来项目中已有很多功能和包,想迁移到mybatis-plus,旧的还是继续用 mybatis和pagehelper,新的准备全部用mybatis-plus。迁移遇到了各种错误,记录一下,特别是这个

由于原来项目中已有很多功能和包,想迁移到mybatis-plus,旧的还是继续用 mybatis和pagehelper,新的准备全部用mybatis-plus。迁移遇到了各种错误,记录一下,特别是这个错误:mybatis-plus org.apache.ibatis.binding.bindingexception: invalid bound statement (not found):,花了差不多一天时间,都差点准备撤子模块了,将旧的一个模块,新的一个模块。

一、mybatis-plus依赖

后面还准备新建对象,把代码生成器也加进来了。

<!-- springboot集成mybatis plus框架 -->
 <dependency>
 <groupid>com.baomidou</groupid>
 <artifactid>mybatis-plus-boot-starter</artifactid>
 <version>${mybatis.plus.version}</version>
 </dependency>
 <!-- mybatis-plus-generator 代码生成器 -->
 <dependency>
 <groupid>com.baomidou</groupid>
 <artifactid>mybatis-plus-generator</artifactid>
 <version>${mybatis.plus.generator.version}</version>
 </dependency>
 <!-- mybatis plus生成代码的模板引擎 -->
 <dependency>
 <groupid>org.apache.velocity</groupid>
 <artifactid>velocity-engine-core</artifactid>
 <version>${velocity.engine.version}</version>
 </dependency>

在这儿遇到第一个问题,原模板有velocity 1.7版本,在代码生成器中有需要用velocity-engine-core,这两个不能同时引用,会有冲突。将velocity引用去掉,在服务器监控程序有一个下面语句不能用,注释掉,好像没有什么影响。
p.setproperty(velocity.output_encoding, constants.utf8);

二、创建代码生成器

参考官方文档,找个单独的包,创建代码生成器。在原来的模块上增加后,各种不能使用,没有办法,新建了一个全新的文件,生产对象代码,创建测试对象,可以运行,到了原来的程序上好多问题,后检查大部分是引用包之间版本冲突造成,主要是:
1、不要保留mybatis的依赖,用最新的mybatis-plus-boot-start就行
2、mybatis-plus版本也会不影响,我用的是3.3.1
 3、包的位置影响很大,接口文件一定要在@mapperscan(“com.xiyou.project.**.mapper”)包含的目录下,
4、配置文件要正确,生成代码要在配置文件包含下:

# mybatis-plus配置
mybatis-plus:
 # 搜索指定包别名
 type-aliases-package: com.xiyou.project.**.domain
 # 配置mapper的扫描,找到所有的mapper.xml映射文件
 mapper-locations: classpath*:mybatis/**/*mapper.xml
// 执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
public class mpgenerator {
 /**
  * <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.isnotempty(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("wu jize");
  gc.setopen(false);
  //实体属性 swagger2 注解
  gc.setswagger2(true);
  mpg.setglobalconfig(gc);
  // 数据源配置
  datasourceconfig dsc = new datasourceconfig();
  dsc.seturl("jdbc:mysql://localhost:33306/xiyou?useunicode=true&characterencoding=utf8&zerodatetimebehavior=converttonull&usessl=true&servertimezone=gmt%2b8");
  // dsc.setschemaname("public");
  dsc.setdrivername("com.mysql.cj.jdbc.driver");
  dsc.setusername("root");
  dsc.setpassword("123123");
  mpg.setdatasource(dsc);
  // 包配置
  packageconfig pc = new packageconfig();
  pc.setmodulename(scanner("模块名"));
  **//生成对模块数据对像的代码保存地**
  pc.setparent("com.xiyou.project");
  **//pojo对象缺省是entity目录,为了与以前的一致,改为domain**
  pc.setentity("domain");
  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<fileoutconfig> foclist = new arraylist<>();
  // 自定义配置会被优先输出
  foclist.add(new fileoutconfig(templatepath) {
   @override
   public string outputfile(tableinfo tableinfo) {
    // 自定义输出文件名 , 如果你 entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
    return projectpath + "/src/main/resources/mybatis/" + pc.getmodulename()
      + "/" + tableinfo.getentityname() + "mapper" + stringpool.dot_xml;
   }
  });
  /*
  cfg.setfilecreate(new ifilecreate() {
   @override
   public boolean iscreate(configbuilder configbuilder, filetype filetype, string filepath) {
    // 判断自定义文件夹是否需要创建
    checkdir("调用默认方法创建的目录");
    return false;
   }
  });
  */
  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.setentitylombokmodel(true);
  strategy.setrestcontrollerstyle(true);
  // 公共父类
 //strategy.setsupercontrollerclass("com.xiyou.framework.web.controller.basecontroller");
  //strategy.setsuperentityclass("com.xiyou.framework.web.domain.baseentity");
  // 写于父类中的公共字段
  //strategy.setsuperentitycolumns("id");
  strategy.setinclude(scanner("表名,多个英文逗号分割").split(","));
  strategy.setcontrollermappinghyphenstyle(true);
  //xml文件名前再增加模块名,不需要,加了重复了
  //strategy.settableprefix(pc.getmodulename() + "_");
  mpg.setstrategy(strategy);
  //mpg.settemplateengine(new freemarkertemplateengine());
  mpg.execute();
 }

三、 invalid bound statement (not found)问题

这个问题搞的时间最长,比较复杂,在官网上是如下描述,比较简单:

  • 检查是不是引入 jar 冲突 检查 mapper.java 的扫描路径 检查是否指定了主键?如未指定,则会导致 selectbyid 相关;
  • id 无法操作,请用注解 @tableid 注解表 id 主键。当然 @tableid 注解可以没有!但是你的主键必须叫
  • id(忽略大小写) sqlsessionfactory不要使用原生的,请使用mybatissqlsessionfactory
  • 检查是否自定义了sqlinjector,是否复写了getmethodlist()方法,该方法里是否注入了你需要的方法

上面方法一遍又一遍查找,没有发现问题,我在全新模块测试对比没有发现任何问题,后来从第参考文章的看到sqlsessionfactory问题得到启发,重点研究这个问题,查然解决了。
 原来的程序有mybatis的配置文件bean,需要替换为mybatis-plus的bean,代码如下:

@configuration
//@mapperscan(basepackages = "com.xiyou.project.map.mapper")
public class mybatisplusconfig {
 @autowired
 private datasource datasource;

 @autowired
 private mybatisplusproperties properties;

 @autowired
 private resourceloader resourceloader = new defaultresourceloader();

 @autowired(required = false)
 private interceptor[] interceptors;

 @autowired(required = false)
 private databaseidprovider databaseidprovider;

 @autowired
 private environment env;
 /**
  * * mybatis-plus分页插件
  *  
  */
 @bean
 public paginationinterceptor paginationinterceptor() {
  paginationinterceptor page = new paginationinterceptor();
  page.setdialect(new mysqldialect());
  return page;
 }

 /**
  * * 这里全部使用mybatis-autoconfigure 已经自动加载的资源。不手动指定 配置文件和mybatis-boot的配置文件同步
  * * 
  * * @return
  * * @throws ioexception
  * 
  */
 @bean
 public mybatissqlsessionfactorybean mybatissqlsessionfactorybean() throws ioexception {
  mybatissqlsessionfactorybean mybatisplus = new mybatissqlsessionfactorybean();
  mybatisplus.setdatasource(datasource);
  mybatisplus.setvfs(springbootvfs.class);
  string configlocation = this.properties.getconfiglocation();
  if (stringutils.isnotblank(configlocation)) {
   mybatisplus.setconfiglocation(this.resourceloader.getresource(configlocation));
  }
  mybatisplus.setconfiguration(properties.getconfiguration());
  mybatisplus.setplugins(this.interceptors);
  mybatisconfiguration mc = new mybatisconfiguration();
  mc.setdefaultscriptinglanguage(mybatisxmllanguagedriver.class);
  // 数据库和java都是驼峰,就不需要,
  //mc.setmapunderscoretocamelcase(false);
  mybatisplus.setconfiguration(mc);
  if (this.databaseidprovider != null) {
   mybatisplus.setdatabaseidprovider(this.databaseidprovider);
  }
  mybatisplus.settypealiasespackage(this.properties.gettypealiasespackage());
  mybatisplus.settypehandlerspackage(this.properties.gettypehandlerspackage());
  mybatisplus.setmapperlocations(this.properties.resolvemapperlocations());
  // 设置mapper.xml文件的路径
  string mapperlocations = env.getproperty("mybatis-plus.mapper-locations");
  resourcepatternresolver resolver = new pathmatchingresourcepatternresolver();
  resource[] resource = resolver.getresources(mapperlocations);
  mybatisplus.setmapperlocations(resource);
  return mybatisplus;
 }
}

替换原来的mybatis配置文件bean后,仍然发以下两个问题:

1、我的application.yml配置文件有配置文件选项,在上面配置文件中也要加载configration内容,存冲突,报下面错误。
property ‘configuration' and ‘configlocation' can not specified with together
将application.yml文件中面来配置项删除。
config-location: classpath:mybatis/mybatis-config.xml

 2、查询表时,没有正确处理字段中驼峰字段名,上面文件中有下面行,注释掉即可。

//mc.setmapunderscoretocamelcase(false);

至此,将原来mybatis项目成功迁移到了mybatis-plus上。

到此这篇关于mybatis迁移到mybatis-plus的实现方法的文章就介绍到这了,更多相关mybatis迁移到mybatis-plus内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网