以下是一些我个人使用mybatis常见问题总结:

插入MySQL数据乱码

这个是因为没配置好jdbc连接字符串,在连接字符串后加上characterEncoding=UTF-8即可,当然连接字符串还可以添加很多其他参数,例如:是否使用SSL连接useSSL=false,服务器时间serverTimezone=CST 。

MySQL连接字符串语法

连接字符串参数一览表

Spring-Boot-Mybatis-Starter无法找不到bean无法启动

这个情况发生在使用spring-boot-mybatis-starter过程中,项目启动后报错:

***************************
APPLICATION FAILED TO START
***************************

Description:

Field recordMapper in com.ryan.project.translaterecorder.service.BaiduTranslateServiceImpl required a bean of type 'com.ryan.project.translaterecorder.dao.RecordMapper' 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.ryan.project.translaterecorder.dao.RecordMapper' in your configuration.

看信息的结果是无法找到对应的mapper实现,先看下接口的写法:

@Repository
public interface RecordMapper {
    void createRecord(@Param("source") String source, @Param("result") String result);
}

解决方法有三种:

更换为@Mapper注解

@Repository注解替换为@Mapper注解

@Mapper
public interface RecordMapper {
    void createRecord(@Param("source") String source, @Param("result") String result);
}

启动类配置mapper接口扫描路径

每个Mapper接口都要配置@Mapper注解太麻烦,可以在启动类配置扫描路径:

@SpringBootApplication
@MapperScan("com.ryan.project.translaterecorder.dao")
public class TranslaterecorderApplication {
    public static void main(String[] args) {
        SpringApplication.run(TranslaterecorderApplication.class, args);
    }
}

用配置类指定mapper接口扫描路径

@Configuration
public class MybatisConfig {
    @Bean
    MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.ryan.project.translaterecorder.dao");
        return mapperScannerConfigurer;
    }
}

小结:

mybatis的mapper扫描路径设置官方文档介绍也是三种方法,与上面的大同小异,无非一个是注解+yml配置一个是xml配置。

MyBatis :Scanning for mappers

SQL绑定失败(Not Found)

这个错误太常见了,基本概括为以下几点:

  • mapper.xml中的namespace与mapper接口不对应
  • 函数名称没有对上,全限定名(类名+方法名,不包括参数)
  • xml文件没有扫描到

对于第三点,maven项目的xml文件应该放到resource里面,不然即使配了路径也没法扫描到。

以下配置没法扫描到xml文件,maven打包后并没有将Java文件夹里面的xml文件打包,运行的时候就会包绑定错误(not found)。

改为把xml文件放到resources文件夹即可: