Java程序员进阶必学技术,三大主流框架SSM(Spring,SpringMvc,Mybatis)之Mybatis框架篇

旧书不厌百回读,熟读精思子自知。——苏轼

今天就要开始将SSM框架的最后一个模块就是M–Mybatis框架了,知识点呢有很多不足的地方,也希望大家再读的时候能够进行补充和完善,好了。接下来正式开始三大主流框架中最后一个框架的学习

Mybatis框架:

1.概念:

Mybatis框架原名ibatis,由apache团队开发,是一个开源的轻量级持久层框架,支持SQL定制,对象关系的高级映射,以及过程存储(SQL语句集,是数据库中一个特别重要的对象)。

2.ORM:

ORM是学习Mybatis必须要了解的一种思想,是为了实现对象关系映射而诞生的思想,解决了如何将实体类中的数据绑定到数据库的难题(感兴趣的可以去了解),而Mybatis就是实现了ORM思想

3.优点:

  1. 底层封装了JDBC的操作流程,大大缩减了代码的重复编写,节省资源,时间
  2. 将SQL语句的书写放到了XML文件中,减弱了对原程序代码的修改,不用每一次都重新编译。

4.底层执行调用逻辑

在学习Mybatis的底层的时候我们先来认识三个类

  1. SqlSessionFactoryBuilder :构造器
  2. SqlSessionFactory :工厂接口
  3. SqlSesion :会话
4.1 SqlSessionFactoryBuilder

SqlSessionFactoryBuilder类可以被实例化也可以丢弃和销毁,主要目的就是为了实例化SessionFactory工厂,在工厂被构建出来之后,就没有作用了,所以该类最合适的作用域范围是在方法内,可以通过SqlSesionFactoryBuilder创建多个工厂对象,通过查看SqlSessionFactoryBuilder源码可以知道,几乎都是build();方法,目的就是通过读取配置信息,通过字节流来创建SqlSessionFactory。
源码分析过程:
1.这是SpringMvc的核心配置文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--核心配置文件-->
<configuration>
    <!--引入外部配置文件-->
    <properties resource="db.properties"/>
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <typeAliases>
        <package name="com.meng.pojo"/>
    </typeAliases>
    <environments default="test">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>

        <environment id="test">
            <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 resource="com/meng/dao/mapper/TeacherMapper.xml"/>
        <mapper resource="com/meng/dao/mapper/StudentMapper.xml"/>
    </mappers>
</configuration>

2.xml文件在SqlSessionFactoryBuilder阶段就被以字节流的形式读到了Build()方法中

String resource = "mybatis-config.xml";
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

3.最终在底层调用的是SqlSessionFactoeyBuilder中的这个方法

public SqlSessionFactory build(InputStream inputStream) {
    return build(inputStream, null, null);
  }

4.在这个方法中build()调用的是这个方法

public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
    try {
      XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
      return build(parser.parse());
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error building SqlSession.", e);
    } finally {
      ErrorContext.instance().reset();
      try {
        inputStream.close();
      } catch (IOException e) {
        // Intentionally ignore. Prefer previous error.
      }
    }
  }

**备注:**XMLConfigBuilder是对mybatis的配置文件进行解析的类,会将解析后的信息存放在Configruation对象中,Configruation对象会贯穿在整个Mybatis的执行流程之中。为mybatis提供各种需要的配置信息
5.在第4布中,return里又调用了一个build()方法,作用把核心配置类的字节流转换成Configruation类型,再通过该方法可获得一个实例化的DefaultSqlSessionFactory

public SqlSessionFactory build(Configuration config) {
    return new DefaultSqlSessionFactory(config);
  }

DefaultSqlSessionFactory:是SqlSessionFactory接口的实现类。

4.2 SqlSessionFactory

SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例。多次重建 SqlSessionFactory 被视为一种代码“坏习惯”。 有很多方法可以做到,最简单的就是使用单例模式或者静态单例模式。
SqlSessionFactory其实是一个接口,其实现类是DefaultSqlSessionFactory
在DefaultSqlSessionFactory源码中,就对核心配置文件也就是Configuration做了解析:

public DefaultSqlSessionFactory(Configuration configuration){
this.configuration=configuration;
}

SqlSessionFactory接口的源码:

public interface SqlSessionFactory {

  SqlSession openSession();

  SqlSession openSession(boolean autoCommit);
  SqlSession openSession(Connection connection);
  SqlSession openSession(TransactionIsolationLevel level);
  SqlSession openSession(ExecutorType execType);
  SqlSession openSession(ExecutorType execType, boolean autoCommit);
  SqlSession openSession(ExecutorType execType, TransactionIsolationLevel level);
  SqlSession openSession(ExecutorType execType, Connection connection);
  Configuration getConfiguration();
}

通过该接口可以获得SqlSession

//既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
    // SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
    // 可以通过 SqlSession 实例来直接执行已映射的 SQL 语句
 public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
4.3 SqlSession

每个线程都应该有它自己的 SqlSession 实例。SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。 绝对不能将 SqlSession 实例的引用放在一个类的静态域,甚至一个类的实例变量也不行。 也绝不能将 SqlSession 实例的引用放在任何类型的托管作用域中,比如 Servlet 框架中的 HttpSession。 如果你现在正在使用一种 Web 框架,考虑将 SqlSession 放在一个和 HTTP 请求相似的作用域中。 换句话说,每次收到 HTTP 请求,就可以打开一个 SqlSession,返回一个响应后,就关闭它。 这个关闭操作很重要,为了确保每次都能执行关闭操作,你应该把这个关闭操作放到 finally 块中。

通过sqlSessionFactory.openSession();获取到Sqlsession对象后,调用sqlSession.getMapper(Mapper接口)可获得Mapper的代理类,通过代理类调用方法就可执行数据库操作,其原理是动态代理。

SqlSession sqlSession = MybatisUtils.getSqlSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        List<Teacher> teachers = mapper.getTeacher();
        for (Teacher teacher : teachers) {
            System.out.println(teacher);
        }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值