mybatis的生命周期

目录

项目配置

pom.xml

mybatis-config.xml

加载配置信息

创建 SqlSessionFactory

创建 SqlSession 对象

获取 Mapper 实例


工作了这些年,每次看到书籍、文档以及他人嘴上说到软件工程的生命周期,我是不赞成的,之前在高中读书的时候,生物课上讲到生命是与蛋白质相关的,然而软件跟蛋白质没有关系,就是一些数据在计算机中创建和销毁,用运行周期来形容更好一些,但是用生命来形容就有点不可理解了。

以一个简单的maven项目来描述这个事情

https://mybatis.org/mybatis-3/zh_CN/getting-started.html

按照官网的讲解,使用mybatis需要做如下几步

项目配置

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>org.example</groupId>
    <artifactId>mybatis-maven</artifactId>
    <version>1.0.0</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <version>8.0.33</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.3.0</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

    </dependencies>

    <build>
        <resources>
            <!-- 扫描 src/main/java 下的配置文件 -->
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/application*.yml</include>
                    <include>**/application*.yaml</include>
                    <include>**/application*.properties</include>
                </includes>
            </resource>
        </resources>
    </build>

</project>

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <!-- 配置文件上下文使用的属性值引用外部文件 -->
    <properties resource="jdbc.properties"></properties>

    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

    <!-- 定义别名,在 mapper 的返回类型中使用 -->
    <typeAliases>
        <typeAlias type="cn.hahaou.mybatis.cache.levelone.entity.Role" alias="role"/>
    </typeAliases>

    <!-- 定义数据库信息,默认使用 development 数据库构建环境 -->
    <environments default="test">
        <environment id="test">
            <!-- 采用 jdbc 事务管理 -->
            <transactionManager type="JDBC"/>
            <!-- 配置数据库连接信息 -->
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <!-- 定义映射器 -->
    <mappers>
        <mapper class="cn.hahaou.mybatis.cache.levelone.mapper.LevelOneRoleMapper"/>
    </mappers>
</configuration>

进行一些基础配置,例如数据库、环境、mapper 。

节点 environments 的 default 的值必须是子节点 environment 的其中任何一个,不然会报错。

配置信息有先后顺序,不然会报错。

加载配置信息

InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");

通过 mybatis 自带的文件加载方式转换为 InputStream。

创建 SqlSessionFactory

SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

SqlSessionFactory 是一个接口,最终使用 SqlSessionFactoryBuilder 通过工厂模式来创建 SqlSessionFactory 的实现类 DefaultSqlSessionFactory。

在整个应用中只需要创建一个,可以使用单例模式来实现。

SqlSessionFactory创建流程

在第二步中完成了一个很重要的事情,将配置文件解析为 mybatis 可用的配置,最终解析的对象为 Configuration,这个很重要,贯穿了 mybatis 的始终。一些运行过程中需要的信息在这里可以获取到

SqlSessionFactory的实现类

创建 SqlSession 对象

DefaultSqlSessionFactory中创建SqlSession对象

鉴于 SqlSession 是一个接口,继承了 Closeable,在使用结束后需要将其关闭。

SqlSession  是线程级别的,非线程安全。

SqlSession的实现类

封装的工具类如下

package cn.hahaou.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtils {

    public static SqlSessionFactory sqlSessionFactory = null;
    public static String resource = "mybatis-config.xml";

    static {
        try (InputStream inputStream = Resources.getResourceAsStream(resource);){
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
        }
    }

    public static SqlSession openSession() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession;
    }
}

SqlSessionFactory 单例模式,全局共享,SqlSession 使用的话需要每次创建。

获取 Mapper 实例

LevelOneRoleMapper roleMapper = sqlSession.getMapper(LevelOneRoleMapper.class);

通过 SqlSession 获取创建的 Mapepr 实例,返回的是一个类型为 MapperProxy 的动态代理类。

在 MapperProxyFactory 中通过工厂模式创建 MapperProxy 对象,里面包含了 DefaultSqlSession、Mapper 接口类、Method 和 MapperMethod 的 map 映射关系。

最终在调用对应的方法时通过反射来执行具体的操作。

整理的时序图如下

mybatis运行周期

至此,整个步骤就完成了,接下来就是具体的业务操作了。

  • 21
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值