源码地址:https://github.com/nieandsun/mybatis-study


1. 学习网站记录

Mybatis官网:https://mybatis.org/mybatis-3/index.html
MyBatis-Spring整合官网:https://mybatis.org/spring/index.html


2. Mybatis、Spring整合框架搭建

感觉比较简单,有不懂或有兴趣的可以clone下来代码看一下,一看肯定就都懂了。不过多解释了,直接上代码。

2.1 pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.nrsc</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>

        <!-- mybatis核心包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.3</version>
        </dependency>

        <!--mybatis/spring整合包-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.3</version>
        </dependency>

        <!--spring核心包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.2.RELEASE</version>
        </dependency>

        <!--数据库驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.17</version>
        </dependency>

        <!--druid连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.31</version>
        </dependency>

        <!--spring-jdbc包,包含了事务管理器-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.2.RELEASE</version>
        </dependency>

        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>

        <!--用于单元测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <!-- 日志相关依赖,非必须 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.10</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.1.2</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>1.1.2</version>
        </dependency>

    </dependencies>

</project>

2.2 配置类

package com.nrsc.mybatis.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.io.IOException;

@EnableTransactionManagement//开启事务
@MapperScan(basePackages = "com.nrsc.mybatis.mapper") //指定Mapper接口的地址
@ComponentScan("com.nrsc.mybatis")
@Configuration
public class SelfDBConfig {

    //创建数据源
    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/mybatis-study?characterEncoding=utf-8&serverTimezone=GMT&useSSL=false");
        return dataSource;
    }

    //注册事务管理器
    @Bean("platformTransactionManager")
    public PlatformTransactionManager platformTransactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }

    //配置SqlSession工厂
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory() throws IOException {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        //指定数据源
        factoryBean.setDataSource(dataSource());
        //指定所有mapper.xml所在路径
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        factoryBean.setMapperLocations(resolver.getResources("classpath:mysql/selfdbmapper/*.xml"));
        return factoryBean;
    }
}

2.3. domain、mapper接口、mapper.xml

这里就不贴在这里了,可从如下两个途径获得:

(1)与《【Mybatis源码探索】 — 开篇 • 搭建一个最简单的Mybatis框架》一致;

(2)也可以直接通过源码获得:https://github.com/nieandsun/mybatis-study

2.4 Service层代码

  • Service接口
package com.nrsc.mybatis.Service;

import com.nrsc.mybatis.domian.TUser;
public interface TUserService {
    TUser selectByPrimaryKey(Integer id);
}
  • Service实现类
package com.nrsc.mybatis.Service.impl;

import com.nrsc.mybatis.Service.TUserService;
import com.nrsc.mybatis.domian.TUser;
import com.nrsc.mybatis.mapper.TUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class TUserServiceImpl implements TUserService {

    @Autowired
    private TUserMapper userMapper;

    @Override
    public TUser selectByPrimaryKey(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }
}

2.5 启动测试类

import com.nrsc.mybatis.Service.TUserService;
import com.nrsc.mybatis.config.SelfDBConfig;
import com.nrsc.mybatis.domian.TUser;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
@Slf4j
public class MybatisSpringStartTest {
    @Test
    public void test1() {
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(SelfDBConfig.class);
        //从IOC容器中获取TUserService对象
        TUserService userService = ac.getBean(TUserService.class);
        
        TUser user = userService.selectByPrimaryKey(1);
        log.info("获取到的数据为:{}", user);
    }
}
3 整体代码结构

整体代码结构如下:
【Mybatis+spring整合源码探秘】--- 开篇 • 搭建一个最简单的Mybatis、Spring整合框架_Mybatis

4 简单测试

启动test1方法,可以在控制台打印出如下结果,表明我搭建的mybati+spring整合框架已经成功。
【Mybatis+spring整合源码探秘】--- 开篇 • 搭建一个最简单的Mybatis、Spring整合框架_Mybatis_02