Spring Boot教程 - 整合Mybatis(基于XML配置)

项目开发中不可避免需要跟数据库打交道,作者开发的项目的中广泛使用Mybatis作为ORM框架。
本文主要讲解在Spring Boot项目中 如何整合Mybatis,基于XML方式配置下一篇中会介绍基于 注解方式的配置。

开发环境

  • JDK 1.8
  • Maven 3.3
  • Spring Boot 1.5.8.RELEASE
  • Mybatis 3.4.4

代码

首先引入spring-boot-starter-parent:

    
    
        org.springframework.boot
        spring-boot-starter-parent
        1.5.8.RELEASE
    

Mybatis依赖:

    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            1.3.1
        

        
        
            mysql
            mysql-connector-java
            ${mysql.connector.version}
        

        
            com.alibaba
            druid
            ${druid.version}
        
    

application.yml

mybatis:
    mapper-locations: classpath:mapper/*.xml
    type-aliases-package: springboot.mybatis.model
    type-handlers-package: springboot.mybatis.typehandler
    configuration:
        map-underscore-to-camel-case: true
        default-fetch-size: 100

spring:
    datasource:
       url: jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
       username: root
       password: root
       driver-class-name: com.mysql.jdbc.Driver

涉及的Mybatis Mapper类和Mapper文件 建议通过Mybatis-Generator来生产,简单、高效。

启动类App

package springboot.mybatis.xml;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * ${DESCRIPTION}
 *
 * @author Ricky Fung
 */
@SpringBootApplication
@MapperScan(basePackages = "com.mindflow.springboot.mybatis.mapper")
public class App {

    public static void main(String[] args) {

        SpringApplication.run(App.class, args);
    }
}

最后,只需要在App类上增加 @MapperScan 注解即可。

源码

传送门:spring-boot-mybatis3-xml-config 查看源码

你可能感兴趣的:(Spring Boot教程 - 整合Mybatis(基于XML配置))