Mybatis迁移到Mybatis

网友投稿 234 2022-11-24


Mybatis迁移到Mybatis

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

一、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}

在这儿遇到第一个问题,原模板有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 {

/**

*

* 读取控制台内容

*

*/

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 focList = new ArrayList<>();

// 自定义配置会被优先输出http://

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 TaEiJ(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上。


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java List集合返回值去掉中括号(&#39;[ ]&#39;)的操作
下一篇:解决IDEA创建maven项目时pom.xml没有变蓝的问题
相关文章

 发表评论

暂时没有评论,来抢沙发吧~