Spring boot模块化项目Mybatis无法找到Mapper解决办法

最近设计系统架构,需要把项目功能子模块化,框架使用Spring Cloud、Spring Boot,在子模块化的时候遇到DAO层分离的问题,比较复杂难解,另外一个就是maven打包的问题,但是相对好解决一点。

首先创建一个子模块(DAO),配置好并且可以启动,然后再创建一个子模块(API),API再maven中继承了DAO模块,配置application.yml文件之后会出现错误:

 Invalid bound statement not found xxxx.xxMapper.selectByxxx()

原因有两个:配置的问题、xml放置位置的问题。

  • 配置
* POM文件加入:
    <dependency>
        <groupId>com.test</groupId>
        <artifactId>dao</artifactId>
        <version>1.0</version>
        <scope>compile</scope>
    </dependency>

* build栏目加入:
    <resource>
        <directory>src/main/resources</directory>
        <includes>
            <include>**/*.*</include>
        </includes>
        <filtering>false</filtering>
    </resource>
    
* 使用注解扫描mapper包
@MapperScan(value = "com.test.mapper.repository.mapper")

* 配置项(application.yml):
    spring:
      application:
        name: api-server
      profiles:
        active: test
      thymeleaf:
        cache: false
        prefix:
          classpath: /templates
      datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        type: org.apache.commons.dbcp2.BasicDataSource
        url: jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC&characterEncoding=utf-8
        username: root
        password: root
        dbcp2:
          initial-size: 5
          max-idle: 100
          min-idle: 5
          max-wait-millis: 3000
          test-on-borrow: true
          test-on-return: false
          test-while-idle: true
          validation-query: SELECT 1
          time-between-eviction-runs-millis: 30000
          soft-min-evictable-idle-time-millis: 1800000
          num-tests-per-eviction-run: 3
          remove-abandoned-timeout: 180
          pool-prepared-statements: true
          max-open-prepared-statements: 15
          
    mybatis:
      type-aliases-package: com.test.mapper.repository
      type-handlers-package: com.test.mapper.repository.mapper
      configuration:
        map-underscore-to-camel-case: true
        default-fetch-size: 100
        default-statement-timeout: 30
      mapper-locations: classpath*:mapper/*.xml

* 最后测试
  • xml位置

位置的问题就是xml需要放置在src/main/resources目录下,我之前是一直放在src/main/java/com/test/repository/src/main/resources目录下,所以一直都是失败的。

配置还需要注意的是:

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

 

Leave a Comment

 
Copyright © 2008-2021 lanxinbase.com Rights Reserved. | 粤ICP备14086738号-3 |