本人微信公众号"aeolian"~

SpringBoot结合Mybatis

jar包引入

<dependency>  
    <groupId>org.springframework.bootgroupId>  
    <artifactId>spring-boot-starter-thymeleafartifactId>  
dependency> 
    
<dependency>  
    <groupId>mysqlgroupId>  
    <artifactId>mysql-connector-javaartifactId>  
dependency>  
    
<dependency>  
    <groupId>org.mybatis.spring.bootgroupId>  
    <artifactId>mybatis-spring-boot-starterartifactId>  
    <version>1.3.0version>  
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/javadirectory>
                <includes>
                    <include>**/*.xmlinclude>
                includes>
            resource>
            <resource>
                <directory>src/main/resourcesdirectory>
                <includes>
                    <include>**/*include>
                includes>
            resource>
        resources>
    build>

 

点赞

Leave a Reply

Your email address will not be published. Required fields are marked *