Mybatis遷移到Mybatis-Plus的實現(xiàn)方法
由于原來項目中已有很多功能和包,想遷移到Mybatis-Plus,舊的還是繼續(xù)用 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引用去掉,在服務器監(jiān)控程序有一個下面語句不能用,注釋掉,好像沒有什么影響。
p.setProperty(Velocity.OUTPUT_ENCODING, Constants.UTF8);
二、創(chuàng)建代碼生成器
參考官方文檔,找個單獨的包,創(chuàng)建代碼生成器。在原來的模塊上增加后,各種不能使用,沒有辦法,新建了一個全新的文件,生產(chǎn)對象代碼,創(chuàng)建測試對象,可以運行,到了原來的程序上好多問題,后檢查大部分是引用包之間版本沖突造成,主要是:
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
// 執(zhí)行 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);
// 數(shù)據(jù)源配置
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("模塊名"));
**//生成對模塊數(shù)據(jù)對像的代碼保存地**
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<>();
// 自定義配置會被優(yōu)先輸出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定義輸出文件名 , 如果你 Entity 設置了前后綴、此處注意 xml 的名稱會跟著發(fā)生變化!!
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) {
// 判斷自定義文件夾是否需要創(chuàng)建
checkDir("調用默認方法創(chuàng)建的目錄");
return false;
}
});
*/
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定義輸出模板
//指定自定義模板路徑,注意不要帶上.ftl/.vm, 會根據(jù)使用的模板引擎自動識別
// 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)問題
這個問題搞的時間最長,比較復雜,在官網(wǎng)上是如下描述,比較簡單:
- 檢查是不是引入 jar 沖突 檢查 Mapper.java 的掃描路徑 檢查是否指定了主鍵?如未指定,則會導致 selectById 相關;
- ID 無法操作,請用注解 @TableId 注解表 ID 主鍵。當然 @TableId 注解可以沒有!但是你的主鍵必須叫
- id(忽略大小寫) SqlSessionFactory不要使用原生的,請使用MybatisSqlSessionFactory
- 檢查是否自定義了SqlInjector,是否復寫了getMethodList()方法,該方法里是否注入了你需要的方法
上面方法一遍又一遍查找,沒有發(fā)現(xiàn)問題,我在全新模塊測試對比沒有發(fā)現(xiàn)任何問題,后來從第參考文章的看到SqlSessionFactory問題得到啟發(fā),重點研究這個問題,查然解決了。
原來的程序有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 已經(jīng)自動加載的資源。不手動指定 配置文件和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);
// 數(shù)據(jù)庫和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后,仍然發(fā)以下兩個問題:
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的實現(xiàn)方法的文章就介紹到這了,更多相關Mybatis遷移到Mybatis-Plus內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
詳解spring boot容器加載完后執(zhí)行特定操作
這篇文章主要介紹了詳解spring boot容器加載完后執(zhí)行特定操作,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-01-01
詳解Spring Boot 使用slf4j+logback記錄日志配置
本篇文章主要介紹了Spring Boot 使用slf4j+logback記錄日志配置,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05
Java Socket聊天室編程(二)之利用socket實現(xiàn)單聊聊天室
這篇文章主要介紹了Java Socket聊天室編程(二)之利用socket實現(xiàn)單聊聊天室的相關資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-09-09
簡單談談ThreadPoolExecutor線程池之submit方法
下面小編就為大家?guī)硪黄唵握務凾hreadPoolExecutor線程池之submit方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-06-06

