Mybatis迁移到Mybatis-Plus的实现方法
由于原来项目中已有很多功能和包,想迁移到Mybatis-Plus,旧的还是继续用Mybatis和PageHelper,新的准备全部用Mybatis-Plus。迁移遇到了各种错误,记录一下,特别是这个错误:mybatis-plusorg.apache.ibatis.binding.BindingException:Invalidboundstatement(notfound):,花了差不多一天时间,都差点准备撤子模块了,将旧的一个模块,新的一个模块。
一、Mybatis-Plus依赖
后面还准备新建对象,把代码生成器也加进来了。
com.baomidou mybatis-plus-boot-starter ${mybatis.plus.version} com.baomidou mybatis-plus-generator ${mybatis.plus.generator.version} org.apache.velocity velocity-engine-core ${velocity.engine.version}
在这儿遇到第一个问题,原模板有Velocity1.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方法控制台输入模块表名回车自动生成对应项目目录中
publicclassMpGenerator{
/**
*
*读取控制台内容
*
*/
publicstaticStringscanner(Stringtip){
Scannerscanner=newScanner(System.in);
StringBuilderhelp=newStringBuilder();
help.append("请输入"+tip+":");
System.out.println(help.toString());
if(scanner.hasNext()){
Stringipt=scanner.next();
if(StringUtils.isNotEmpty(ipt)){
returnipt;
}
}
thrownewMybatisPlusException("请输入正确的"+tip+"!");
}
publicstaticvoidmain(String[]args){
//代码生成器
AutoGeneratormpg=newAutoGenerator();
//全局配置
GlobalConfiggc=newGlobalConfig();
StringprojectPath=System.getProperty("user.dir");
gc.setOutputDir(projectPath+"/src/main/java");
gc.setAuthor("wujize");
gc.setOpen(false);
//实体属性Swagger2注解
gc.setSwagger2(true);
mpg.setGlobalConfig(gc);
//数据源配置
DataSourceConfigdsc=newDataSourceConfig();
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);
//包配置
PackageConfigpc=newPackageConfig();
pc.setModuleName(scanner("模块名"));
**//生成对模块数据对像的代码保存地**
pc.setParent("com.xiyou.project");
**//pojo对象缺省是entity目录,为了与以前的一致,改为domain**
pc.setEntity("domain");
mpg.setPackageInfo(pc);
//自定义配置
InjectionConfigcfg=newInjectionConfig(){
@Override
publicvoidinitMap(){
//todonothing
}
};
//如果模板引擎是freemarker
//StringtemplatePath="/templates/mapper.xml.ftl";
//如果模板引擎是velocity
StringtemplatePath="/templates/mapper.xml.vm";
//自定义输出配置
ListfocList=newArrayList<>();
//自定义配置会被优先输出
focList.add(newFileOutConfig(templatePath){
@Override
publicStringoutputFile(TableInfotableInfo){
//自定义输出文件名,如果你Entity设置了前后缀、此处注意xml的名称会跟着发生变化!!
returnprojectPath+"/src/main/resources/mybatis/"+pc.getModuleName()
+"/"+tableInfo.getEntityName()+"Mapper"+StringPool.DOT_XML;
}
});
/*
cfg.setFileCreate(newIFileCreate(){
@Override
publicbooleanisCreate(ConfigBuilderconfigBuilder,FileTypefileType,StringfilePath){
//判断自定义文件夹是否需要创建
checkDir("调用默认方法创建的目录");
returnfalse;
}
});
*/
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
//配置模板
TemplateConfigtemplateConfig=newTemplateConfig();
//配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm,会根据使用的模板引擎自动识别
//templateConfig.setEntity("templates/entity2.java");
//templateConfig.setService();
//templateConfig.setController();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
//策略配置
StrategyConfigstrategy=newStrategyConfig();
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(newFreemarkerTemplateEngine());
mpg.execute();
}
三、Invalidboundstatement(notfound)问题
这个问题搞的时间最长,比较复杂,在官网上是如下描述,比较简单:
- 检查是不是引入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")
publicclassMybatisPlusConfig{
@Autowired
privateDataSourcedataSource;
@Autowired
privateMybatisPlusPropertiesproperties;
@Autowired
privateResourceLoaderresourceLoader=newDefaultResourceLoader();
@Autowired(required=false)
privateInterceptor[]interceptors;
@Autowired(required=false)
privateDatabaseIdProviderdatabaseIdProvider;
@Autowired
privateEnvironmentenv;
/**
**mybatis-plus分页插件
*
*/
@Bean
publicPaginationInterceptorpaginationInterceptor(){
PaginationInterceptorpage=newPaginationInterceptor();
page.setDialect(newMySqlDialect());
returnpage;
}
/**
**这里全部使用mybatis-autoconfigure已经自动加载的资源。不手动指定配置文件和mybatis-boot的配置文件同步
**
**@return
**@throwsIOException
*
*/
@Bean
publicMybatisSqlSessionFactoryBeanmybatisSqlSessionFactoryBean()throwsIOException{
MybatisSqlSessionFactoryBeanmybatisPlus=newMybatisSqlSessionFactoryBean();
mybatisPlus.setDataSource(dataSource);
mybatisPlus.setVfs(SpringBootVFS.class);
StringconfigLocation=this.properties.getConfigLocation();
if(StringUtils.isNotBlank(configLocation)){
mybatisPlus.setConfigLocation(this.resourceLoader.getResource(configLocation));
}
mybatisPlus.setConfiguration(properties.getConfiguration());
mybatisPlus.setPlugins(this.interceptors);
MybatisConfigurationmc=newMybatisConfiguration();
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文件的路径
StringmapperLocations=env.getProperty("mybatis-plus.mapper-locations");
ResourcePatternResolverresolver=newPathMatchingResourcePatternResolver();
Resource[]resource=resolver.getResources(mapperLocations);
mybatisPlus.setMapperLocations(resource);
returnmybatisPlus;
}
}
替换原来的Mybatis配置文件Bean后,仍然发以下两个问题:
1、我的application.yml配置文件有配置文件选项,在上面配置文件中也要加载configration内容,存冲突,报下面错误。
Property‘configuration'and‘configLocation'cannotspecifiedwithtogether
将application.yml文件中面来配置项删除。
config-Location:classpath:mybatis/mybatis-config.xml
2、查询表时,没有正确处理字段中驼峰字段名,上面文件中有下面行,注释掉即可。
//mc.setMapUnderscoreToCamelCase(false);
至此,将原来mybatis项目成功迁移到了mybatis-plus上。
到此这篇关于Mybatis迁移到Mybatis-Plus的实现方法的文章就介绍到这了,更多相关Mybatis迁移到Mybatis-Plus内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。