spring boot 整合mybatis

1,添加mybatis起步依赖

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.0</version>
        </dependency>

2,使用mysql数据库,加入mysql依赖

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

3,在启动类加入@MapperScan注解

@SpringBootApplication
/*
* 这个注解用户扫描dao所在的包
* */
@MapperScan(basePackages = "com.test.dao")
public class Day42SpringbootMybatisApplication {

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

}

4,配置,这样我们就不用和在spring里面一样,在resource目录下还得一一对应添加目录了com/test/dao/UserDao.xml

我们可以直接在resource目录下写一个我们自定义的目录,然后把所有的映射文件放在该目录下即可【这一步不是必须得做,这样做只不过方便一些】

mysql:url必须带上时区&serverTimezone=Asia/Shanghai

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai

#mybatis配置
#mapper-locations: classpath:mapper/UserMapper.xml指定加载这个文件


mybatis:
  mapper-locations: classpath:mapper/*Mapper.xml
  mybatis.type-aliases-package=配置entity实体类的别名包扫描

如果你没有在启动类上进行Mapper 接口的包扫描,那么请在Mapper接口上添加上 @Mapper 注解。

  • @MapperScan 注解是配置 MyBatis Mapper 接口包扫描的标准方法。
  • spring.mybatis.mapper-locations 属性用于指定 XML 映射文件的位置,不用于 Mapper 接口的包扫描。
  • 在配置文件中配置 Mapper 接口的包扫描可能不被所有版本的 Spring Boot 支持,推荐使用注解方式。
posted @ 2021-08-30 14:52  在线电影制作人  阅读(6)  评论(0)    收藏  举报  来源