集成MyBatis

MyBatis 官方为了方便 Spring Boot 集成 MyBatis,专门提供了一个符合 Spring Boot 规范的 starter 项目 mybatis-spring-boot-starter,项目地址是 https://github.com/mybatis/spring-boot-starter

Maven 依赖坐标如下。

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

现在只需要在 pom.xml 中添加上面的依赖即可,符合 Spring Boot 规范的 starter 依赖都会按照默认的配置方式在系统启动时自动配置好,因此不用对 MyBatis 进行任何额外的配置,MyBatis 就已经集成好了。

按照如下步骤添加一个简单的例子来使用 MyBatis。

  1. 添加 CountryMapper 接口

    先在 tk.mybatis.springboot.model 包下新建 Country 类。

    public class Country {
    
        /**
         * 主键
         */
        private Long id;
        /**
         * 国家名称
         */
        private String countryname;
        /**
         * 国家代码
         */
        private String countrycode;
        // 省略 getter 和 setter
    }

    然后在 tk.mybatis.springboot.mapper 包下新建 CountryMapper 接口。

    package cn.liaozh.mybatis2.ch10.boot.mapper;
    
    import cn.liaozh.mybatis2.ch10.boot.model.Country;
    import org.apache.ibatis.annotations.Mapper;
    
    import java.util.List;
    
    @Mapper
    public interface CountryMapper {
        /**
         * 查询全部
         * @return 全部信息
         */
        List<Country> listAll();
    }

    这个接口和前几章中的接口最大的区别是,这里使用了 @Mapper 注解,增加这个注解之后,Spring 启动时会自动扫描该接口,这样就可以在需要使用时直接注入 Mapper 了。

  2. 添加 CountryMapper.xml 映射文件

    在 src/main/resources 下面创建 mapper 目录,然后新建 CountryMapper.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="cn.liaozh.mybatis2.ch10.boot.mapper.CountryMapper">
    
        <select id="listAll" resultType="Country">
            SELECT
                id,
                countryname,
                countrycode
            FROM country
        </select>
    
    </mapper>
  3. 配置 MyBatis

    在 application.properties 配置文件中添加如下内容。

    #映射文件的路径,支持 Ant 风格的通配符,多个配置可以使用英文逗号隔开
    mybatis.mapperLocations=classpath:mapper/*.xml
    #类型别名包配置,只能指定具体的包,多个配置可以使用英文逗号隔开
    mybatis.typeAliasesPackage=tk.mybatis.springboot.model

    这两个配置的含义可以先看上面的注释,关于 Mybatis 的属性配置,在下一节会做详细介绍。

  4. 修改 Application 类

添加如下测试代码。

@SpringBootApplication
public class BootApplication implements CommandLineRunner {

    @Autowired
    private CountryMapper countryMapper;

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

    /**
     * Spring Boot项目启动完成后自动执行
     *
     * @param args
     * @throws Exception
     */
    @Override
    public void run(String... args) throws Exception {
        System.out.println(countryMapper.listAll());
    }
}

在这个类中,我们通过 @Autowired 注解注入 CountryMapper,在 run 方法中执行了 selectAll 方法,重新运行 Application 类,部分日志如下(经过内容删减)。

到这里,Spring Boot 集成 MyBatis 就完成了。其中还存在很多和配置相关的细节,并且我们还想把前面章节中开发的 MyBatis 代码集成到 Spring Boot 中,那么继续来看下一节的配置介绍。