SpringBoot结合Mybatis

jar包引入

<dependency>  
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-thymeleaf</artifactId>  
</dependency> 
    
<dependency>  
    <groupId>mysql</groupId>  
    <artifactId>mysql-connector-java</artifactId>  
</dependency>  
    
<dependency>  
    <groupId>org.mybatis.spring.boot</groupId>  
    <artifactId>mybatis-spring-boot-starter</artifactId>  
    <version>1.3.0</version>  
</dependency>

配置application.properties

如果是properties文件,配置如下

#Mybatis配置
spring.datasource.url=jdbc:mysql://localhost:3306/demo?characterEncoding=utf8&characterSetResults=utf8&autoReconnect=true&failOverReadOnly=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
mybatis.type-aliases-package=com.example.demo1.entity,com.example.demo2.entity
mybatis.mapperLocations=classpath:mappers/*.xml

配置application.yml

如果是yml文件,配置如下

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/javaelec?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver

mybatis:
  mapper-locations: classpath:com/javaelec/*/mapper/*Mapper.xml
  type-aliases-package: com.example.demo1.entity,com.example.demo2.entity

扫描Mapper接口

方法一:在启动类上加@MapperScan

@MapperScan("com.javaelec")
@SpringBootApplication
public class WxApplication {

  public static void main(String[] args) {
    SpringApplication.run(WxApplication.class, args);
  }
}

方法二:在mapper接口文件上加@Mapper注解

Invalid bound statement (not found)

启动后依然报错,发现编译后的文件不包括xml,需要在pom.xml中添加

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*</include>
                </includes>
            </resource>
        </resources>
    </build>
原文地址:https://www.cnblogs.com/aeolian/p/12317497.html