SpringBoot里配置mybatis的十个注意点

1.添加依赖

implementation org.mybatis.spring.boot:mybatis-spring-boot-starter:2.0.0
testCompile org.mybatis.spring.boot:mybatis-spring-boot-starter-test:2.0.0

2.新建mapper接口文件, 与mapper.xml文件

3.mapper 接口文件前有@Mapper注释,以便于自动注入

4.mapper.xml的头为

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

5.mapper.xml中的namespace路径要从类目录具体到mapper接口文件名,即copy reference path

6.mapper.xml中映射的实体类要有getter, setter方法,如是用lombok插件不要忘加依赖,以及在实体类前加@Data

7.mapper.xml中的id要与接口文件中的接口函数名对应,参数类型,返回值类型也要一一对应

8.mapper.xml中sql语句中的#{}中的名对应接口函数的参数名。

9.application.yml中要保证 mybatis: mapper-locations: 路径的正确,精确到mapper.xml,如以下是定位到resource -> mappers -> mapper.xml classpath*:后没有空格, mybatis:和mapper-locations:后面有

mybatis:
  mapper-locations: classpath*:/**/mapper.xml

10.启动类前要加@MapperScan(basePackages="")定位到接口文件

后续有话再加

经验分享 程序员 微信小程序 职场和发展