springboot整合mybatis mapper扫描问题

springboot整合mybatis,想要mapper类和mapper.xml能够被spring容器扫描到,需要进行以下配置

1.扫描Mapper接口类
(1)给接口类加上@Mapper注解(需要在每个类上都添加@Mapper注解)

加@Repository或者@Component都不管用,必须得@Mapper注解才行。

(2)在启动类上加@MapperScan注解(只需在启动类上添加一次即可)

单个包:@MapperScan(“com.example.demo.**.dao”)

多个包:@MapperScan({“com.mysiteforme.admin.dao”,“com.zipon.tpf.dao”})

补充:

@Mapper和@MapperScan注解都是mybatis的注解,而@Component和@ComponentScan注解都是spring的,在mybatis的应用场景下,用mybatis的注解。

2.扫描*Mapper.xml文件
(1)*Mapper.xml文件放在resources下时

在这里插入图片描述

application.yml:

mybatis:
  mapper-locations: classpath*:mapper/*Mapper.xml
  type-aliases-package: com.xiao.learn.entity
(2)*Mapper.xml文件在java目录下时

该路径下,默认在编译时不会把静态文件编译到target目录下,会找不到

这种问题在启动时没什么异常,但是当你调用这个mapper的方法时就会抛出:

BindingException: Invalid bound statement (not found)

解决办法是在pom.xml(maven项目)中的build标签里加入:

<resources>
    <resource>
        <directory>${basedir}/src/main/java</directory>
        <includes>
            <include>**/*.xml</include>
        </includes>
    </resource>
</resources>

扫描配置:

application.properties

mybatis.mapper-locations=classpath:org/sang/springboot/mapper/xml/*.xml
mybatis.type-aliases-package=org.sang.springboot.entity

如果*Mapper.xml文件跟mapper类在同一文件夹下,则不需要进行上面的配置

多个路径时中间用","号隔开即可*:classpath:com/learn/shiro/mapper/xmls/.xml,classpath:xmls/.xml


版权声明:本文为qq_35096670原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。