springboot整合mybatis出的两个问题
在springboot整合mybatis,使用tk.mybatis的时候,遇到了两个问题。写了个简单的demo后解决,在这里记录一下。
问题一:项目无法正常启动
报错内容
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-07-14 23:41:17.390 ERROR 108492 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field mapper in com.cn.my.service.impl.UserMoneyServiceImpl required a bean of type 'com.cn.my.utils.mapper.UserMoneyMapper' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.cn.my.utils.mapper.UserMoneyMapper' in your configuration.
问题原因
未在启动类中配置扫描包,增加如下mapper扫描即可
@SpringBootApplication
//扫描 mybatis mapper 包路径
@MapperScan(basePackages = "com.cn.my.utils.mapper")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
问题二:service调用mapper方法时报错
报错内容
在service中调用mapper接口方法的时候,报出以下问题
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.builder.BuilderException: Error invoking SqlProvider method (tk.mybatis.mapper.provider.base.BaseSelectProvider.dynamicSQL). Cause: java.lang.InstantiationException: tk.mybatis.mapper.provider.base.BaseSelectProvider
at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:77)
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:446)
问题原因
在启动类中导入了错误MapperScan类,应该导入tx.mytatis包下的,而代码中导入了org.mybatis下的,修正的代码如下
package com.cn.my;
// import org.mybatis.spring.annotation.MapperScan; 这是错误的导包
import tk.mybatis.spring.annotation.MapperScan; // 这是正确的导包
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
//扫描 mybatis mapper 包路径
@MapperScan(basePackages = "com.cn.my.utils.mapper")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}