在springboot与Mybatis项目中,经常会出现上述错误,很久不使用mybatis,碰到这种问题就很头大。特此总结。
1、pom.xml文件配置resources
首先,这次我自己的项目报错,是因为pom文件缺少配置resources,它来指定mapper.xml所在文件位置,不然mapper.xml文件就会被漏掉。
<resources>
<resource>
<directory>src/main/</directory>
<!-- 此配置不可缺,否则mybatis的Mapper.xml将会丢失 -->
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<!--指定资源的位置-->
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
补充解释:
和mapper接口文件相互绑定的 .xml文件不是代码,无需编译,但是需要指定在编译时将指定的资源文件(此处为 .xml文件)拷贝到对应目录下(此处应当为 编译好之后 类文件的对应目录)。以上操作步骤就是针对这个原因。
2、mapper.xml文件的namespace是mapper接口文件的全类名
mapper.xml文件中的id和mapper接口文件中的方法名称要一致
3、Springboot项目中application.yml文件,mybatis相关配置
spring:
application:
name: mybatisdemo
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
name: lucene
username: root
password: root
url: jdbc:mysql://localhost:3306/lucene?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
resources:
static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/templates/,classpath:/static/,classpath:/public/,file:${web.upload-path}
chain:
strategy:
content:
enabled: true
paths: /**
mybatis:
type-aliases-package: com.example.mybatisdemo.eneities
mapper-locations: classpath:/resources/Mybatis/mapper/*.xml
server:
port: 8080