SpringBoot集成mybatis

SpringBoot集成mybatis

 

 

官网: http://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/

 https://mybatis.net.cn/

 

1、maven依赖:

<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.2</version>
</dependency>

 

2、yml配置 

#mybatis的相关配置
mybatis:
  #mapper配置文件
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.zhg.demo.mybatis.entity
  #开启驼峰命名
  configuration:
    map-underscore-to-camel-case: true

 

3、在 Spring Boot 启动类中添加 @MapperScan 注解,扫描 Mapper / dao文件夹:

@SpringBootApplication
@MapperScan("com.dw.study.mapper")
public class Application {

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

}

 配置扫描 Mybatis 的 interface

在和 SpringBoot 整合后,扫描 Mybatis 的接口,生成代理对象是一件很简单的事,只需要一个注解即可。
@Mapper
该注解标注在 Mybatis 的interface 类上,SpringBoot 启动之后会扫描后会自动生成代理对象。实例如下:

@Mapper
public interface UserInfoMapper {
  int insert(UserInfo record);
  int insertSelective(UserInfo record);
}

缺点:每个interface 都要标注一个,很鸡肋,一个项目中的 interface 少说也有上百个吧。
@MapperScan
@Mapper 注解的升级版,标注在配置类上,用于一键扫描 Mybatis 的interface 。使用也是很简单的,直接指定接口所在的包即可,如下:

@MapperScan({"com.xxx.dao"})
public class ApiApplication {}

@MapperScan@Mapper 这两个注解千万不要重复使用。优点:一键扫描,不用每个 interface 配置。

 

mybatis.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="">
 
</mapper>

 

posted @ 2018-06-13 16:04  邓维-java  阅读(194)  评论(0编辑  收藏  举报