美文网首页
从Java原生的Jdbc操作数据库到MyBatis 1

从Java原生的Jdbc操作数据库到MyBatis 1

作者: lclandld | 来源:发表于2022-03-04 17:19 被阅读0次

    一、最先我们操作数据库就是这么几步

    image.png

    二、框架该如何做到优化

    image.png

    三、看看具体的MyBatis

    MyBatis感觉核心就两步

    • 构建,就是解析我们写的xml配置(mybatis-config.xml和mapper.xml),将其变成它所需要的对象
    • 执行,在构建完成的基础上,执行我们的SQL,完成与Jdbc的交互

    1、mybatis-config.xml配置文件

    mybatis-config.xml配置文件中包含了对 MyBatis 系统的核心设置,包括获取数据库连接实例的数据源(DataSource)以及决定事务作用域和控制方式的事务管理器(TransactionManager)、加载mapper.xml

    <?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>
       <!-- 和spring整合后 environments配置将废除 -->
      <environments default="development">
        <environment id="development">
          <!-- 使用jdbc事务管理 -->
          <transactionManager type="JDBC"/>
          <!-- 数据库连接池 -->
          <dataSource type="POOLED">
            <property name="driver" value="com.mysql.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://xxxxxxx:3306/test?characterEncoding=utf8"/>
            <property name="username" value="root"/>
            <property name="password" value="root"/>
          </dataSource>
        </environment>
      </environments>
    
      <!-- 加载mapper.xml -->
      <mappers>
          <!-- 注意 mapper节点中,可以使用resource/url/class三种方式获取mapper-->
          <!-- 通过配置文件路径 -->
         <mapper resource="org/mybatis/example/BlogMapper.xml"/>
         <!-- 通过Java全限定类名 -->
         <mapper class="org.mybatis.example.TestMapper"/>
         <!-- 通过url, 通常是mapper不在本地时用 -->
        <mapper url=""/>
        <!-- 通过包名 -->
        <package name="org.mybatis.example"/>
      </mappers>
    </configuration>
    

    2、BlogMapper.xml

    这个文件中写了我们查询数据库所用的SQL

    <?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="org.mybatis.example.BlogMapper">
      <select id="selectBlog" resultType="Blog">
        select * from Blog where id = #{id}
      </select>
    </mapper>
    

    3、如何将这两个配置文件读取成Java对象的

    • 对于mybatis-config.xml
    String resource = "org/mybatis/example/mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    
    • 对于BlogMapper.xml
    //第一种方式读取BlogMapper.xml
    try (SqlSession session = sqlSessionFactory.openSession()) {
      Blog blog = (Blog) session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);
    }
    
    //第二种方式读取BlogMapper.xml
    try (SqlSession session = sqlSessionFactory.openSession()) {
      BlogMapper mapper = session.getMapper(BlogMapper.class);
      Blog blog = mapper.selectBlog(101);
    }
    

    第二种代码不仅更清晰,更加类型安全,还不用担心可能出错的字符串字面值以及强制类型转换。

    4、最基本完整的MyBatis代码

        public static void main(String[] args) throws Exception {
            //第一步读取mybatis-config.xml
            String resource = "org/mybatis/example/mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            //第二步利用SqlSessionFactoryBuilder创建SqlSessionFactory((这里用到了工厂模式和构建者模式)) 
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            //第三步:利用sqlSessionFactory去获取 SqlSession 
            SqlSession sqlSession = sqlSessionFactory.openSession();
            //第四步:利用SqlSession 获取Mapper
            BlogMapper mapper = session.getMapper(BlogMapper.class);
            //传入参数,进行具体的sql查询
            Blog blog = mapper.selectBlog(101);
            //关闭连接
            sqlSession.close();
            sqlSession.commit();
        }  
    
    

    以上四部的流程图大概如下


    image.png

    四、MyBatis3.5.6源码分析

    第一步:解析mybatis-config.xml

    • 看SqlSessionFactoryBuilder.build()里面的方法
      public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
        try {
          //解析mybatis-config.xml
          //XMLConfigBuilder  构造者
          XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
          //parse(): 解析mybatis-config.xml里面的节点
          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.
          }
        }
      }
    
    • 进入parse()
      注意parse的返回值,Configuration,这个与mybatis-config.xml中的<configuration>节点是关联起来的
      public Configuration parse() {
        //改标识标识只能被解析一次
        if (parsed) {
          throw new BuilderException("Each XMLConfigBuilder can only be used once.");
        }
        parsed = true;
        //解析<configuration>节点
        parseConfiguration(parser.evalNode("/configuration"));
        return configuration;
      }
    
    • 进入parseConfiguration()
      对比着mybatis-config.xml中的<configuration></configuration>去看,一些在就能明白了,configuration可以再去看看官网的,有些我们没配置,比如properties、settings、typeAliases、objectFactory、objectWrapperFactory、reflectorFactory、databaseIdProvider、typeHandlers等这些我们都没配置,具体的配置请参考官网
      private void parseConfiguration(XNode root) {
        try {
          // issue #117 read properties first
          propertiesElement(root.evalNode("properties"));
          Properties settings = settingsAsProperties(root.evalNode("settings"));
          loadCustomVfs(settings);
          loadCustomLogImpl(settings);
          typeAliasesElement(root.evalNode("typeAliases"));
          pluginElement(root.evalNode("plugins"));
          objectFactoryElement(root.evalNode("objectFactory"));
          objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
          reflectorFactoryElement(root.evalNode("reflectorFactory"));
          settingsElement(settings);
          // read it after objectFactory and objectWrapperFactory issue #631
          environmentsElement(root.evalNode("environments"));
          databaseIdProviderElement(root.evalNode("databaseIdProvider"));
          typeHandlerElement(root.evalNode("typeHandlers"));
         //这一步的解析看第二步:解析mapper.xml
          mapperElement(root.evalNode("mappers"));
        } catch (Exception e) {
          throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
        }
      }
    

    第二步:解析mapper.xml

    在上面的最后一步是解析mappers
    mapperElement(root.evalNode("mappers"));

      private void mapperElement(XNode parent) throws Exception {
        if (parent != null) {
          for (XNode child : parent.getChildren()) {
            if ("package".equals(child.getName())) {
              String mapperPackage = child.getStringAttribute("name");
              configuration.addMappers(mapperPackage);
            } else {
              String resource = child.getStringAttribute("resource");
              String url = child.getStringAttribute("url");
              String mapperClass = child.getStringAttribute("class");
             //优先级 resource>url>mapperClass
              if (resource != null && url == null && mapperClass == null) {
                ErrorContext.instance().resource(resource);
               //通过XMLMapperBuilder解析XXXMapper.xml,构建的XMLMapperBuilde传入了configuration,所以之后肯定会将mapper封装到configuration对象中去
                InputStream inputStream = Resources.getResourceAsStream(resource);
                XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
                mapperParser.parse();
              } else if (resource == null && url != null && mapperClass == null) {
                ErrorContext.instance().resource(url);
                InputStream inputStream = Resources.getUrlAsStream(url);
                XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
                mapperParser.parse();
              } else if (resource == null && url == null && mapperClass != null) {
                Class<?> mapperInterface = Resources.classForName(mapperClass);
                configuration.addMapper(mapperInterface);
              } else {
                throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
              }
            }
          }
        }
      }
    
    • 先看通过resource来解析mapper.xml
      public void parse() {
        if (!configuration.isResourceLoaded(resource)) {
         //解析mapper文件节点
          configurationElement(parser.evalNode("/mapper"));
          configuration.addLoadedResource(resource);
         //绑定Namespace里面的Class对象
          bindMapperForNamespace();
        }
        //重新解析之前解析不了的节点
        parsePendingResultMaps();
        parsePendingCacheRefs();
        parsePendingStatements();
      }
    
    • configurationElement(parser.evalNode("/mapper"));
      拿到里面配置的配置项 ,最后封装成一个MapperedStatemanet
      [图片上传中...(image.png-3fd741-1646375471539-0)]
      private void configurationElement(XNode context) {
        try {
         //获取命名空间 namespace,这个非常重要,mybatis后面会通过namespace动态代理我们的Mapper接口
          String namespace = context.getStringAttribute("namespace");
          if (namespace == null || namespace.isEmpty()) {
            throw new BuilderException("Mapper's namespace cannot be empty");
          }
          builderAssistant.setCurrentNamespace(namespace);
          //解析缓存节点,平时实际写sql没写这个
          cacheRefElement(context.evalNode("cache-ref"));
          cacheElement(context.evalNode("cache"));
          parameterMapElement(context.evalNodes("/mapper/parameterMap"));
          resultMapElements(context.evalNodes("/mapper/resultMap"));
          sqlElement(context.evalNodes("/mapper/sql"));
         //解析增删改查
          buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
        } catch (Exception e) {
          throw new BuilderException("Error parsing Mapper XML. The XML location is '" + resource + "'. Cause: " + e, e);
        }
      }
    
    

    上面解析的namespace、/mapper/resultMap、/mapper/sql、select|insert|update|delete就如下面


    image.png
    • 解析增删改查节点
      buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
      根据这个名字就可以了解到是用来构造一个Statement,用过原生Jdbc的都知道,Statement就是我们操作数据库的对象。就是我们文章最先的那个流程图的第三步(创建Statement对象)
      private void buildStatementFromContext(List<XNode> list) {
        if (configuration.getDatabaseId() != null) {
          buildStatementFromContext(list, configuration.getDatabaseId());
        }
        buildStatementFromContext(list, null);
      }
    
      private void buildStatementFromContext(List<XNode> list, String requiredDatabaseId) {
        for (XNode context : list) {
          final XMLStatementBuilder statementParser = new XMLStatementBuilder(configuration, builderAssistant, context, requiredDatabaseId);
          try {
            statementParser.parseStatementNode();
          } catch (IncompleteElementException e) {
           //xml语句有问题时 存储到集合中 等解析完能解析的再重新解析
            configuration.addIncompleteStatement(statementParser);
          }
        }
      }
    
    • 来看真正的解析工作
      statementParser.parseStatementNode();这段代码比较长
      public void parseStatementNode() {
       //获取<select id="xxx">中的id
        String id = context.getStringAttribute("id");
        String databaseId = context.getStringAttribute("databaseId");
        //这儿跟一下源码进去看可以看到MappedStatement ,MyBatis中很亲切的一个大对象
       // MappedStatement previous = this.configuration.getMappedStatement(id, false); // issue #2
        if (!databaseIdMatchesCurrent(id, databaseId, this.requiredDatabaseId)) {
          return;
        }
    
        //获取节点名  select update delete insert
        String nodeName = context.getNode().getNodeName();
        // SqlCommandType 是一个枚举型,里面的值是UNKNOWN,  INSERT, UPDATE, DELETE, SELECT,FLUSH;
        SqlCommandType sqlCommandType = SqlCommandType.valueOf(nodeName.toUpperCase(Locale.ENGLISH));
       //判断是否是查询
        boolean isSelect = sqlCommandType == SqlCommandType.SELECT;
       //是否刷新缓存 默认:增删改刷新 查询不刷新
        boolean flushCache = context.getBooleanAttribute("flushCache", !isSelect);
       //是否使用二级缓存 默认值:查询使用 增删改不使用
        boolean useCache = context.getBooleanAttribute("useCache", isSelect);
        boolean resultOrdered = context.getBooleanAttribute("resultOrdered", false);
    
        // Include Fragments before parsing 
        XMLIncludeTransformer includeParser = new XMLIncludeTransformer(configuration, builderAssistant);
        //看代码后的图  替换Includes标签为对应的sql标签里面的值
        includeParser.applyIncludes(context.getNode());
        //获取parameterType名
        String parameterType = context.getStringAttribute("parameterType");
        // value = (Class<T>) Resources.classForName(string);
        Class<?> parameterTypeClass = resolveClass(parameterType);
    
        //解析配置的自定义脚本语言驱动 这里为null,走进去可以看到是设置了默认的 
        //languageRegistry.getDefaultDriver(),是放到
       // private final Map<Class<? extends LanguageDriver>, LanguageDriver> LANGUAGE_DRIVER_MAP = new HashMap<>();一个HashMap中的
        String lang = context.getStringAttribute("lang");
        LanguageDriver langDriver = getLanguageDriver(lang);
    
        // Parse selectKey after includes and remove them.
       //SelectKey在Mybatis中是为了解决Insert数据时不支持主键自动生成的问题,他可以很随意的设置生成主键的方式 
      //SelectKey需要注意order属性,像Mysql一类支持自动增长类型的数据库中,order需要设置为after才会取到正确的值。
        processSelectKeyNodes(id, parameterTypeClass, langDriver);
    
        // Parse the SQL (pre: <selectKey> and <include> were parsed and removed)
        //设置主键自增规则
        KeyGenerator keyGenerator;
        String keyStatementId = id + SelectKeyGenerator.SELECT_KEY_SUFFIX;
        keyStatementId = builderAssistant.applyCurrentNamespace(keyStatementId, true);
        if (configuration.hasKeyGenerator(keyStatementId)) {
          keyGenerator = configuration.getKeyGenerator(keyStatementId);
        } else {
          keyGenerator = context.getBooleanAttribute("useGeneratedKeys",
              configuration.isUseGeneratedKeys() && SqlCommandType.INSERT.equals(sqlCommandType))
              ? Jdbc3KeyGenerator.INSTANCE : NoKeyGenerator.INSTANCE;
        }
       
       //根据sql来判断是否需要动态解析 如果没有动态sql语句且 只有#{}参数的时候 直接静态解析,使用?占位 当有 ${} 不解析
        SqlSource sqlSource = langDriver.createSqlSource(configuration, context, parameterTypeClass);
        //获取StatementType,可以理解为Statement和PreparedStatement
        StatementType statementType = StatementType.valueOf(context.getStringAttribute("statementType", StatementType.PREPARED.toString()));
        Integer fetchSize = context.getIntAttribute("fetchSize");
        Integer timeout = context.getIntAttribute("timeout");
        String parameterMap = context.getStringAttribute("parameterMap");
        //获取返回值类型名
        String resultType = context.getStringAttribute("resultType");
        // 实际最后就调用的这个value = (Class<T>) Resources.classForName(string);
        Class<?> resultTypeClass = resolveClass(resultType);
        //获取resultMap
        String resultMap = context.getStringAttribute("resultMap");
        String resultSetType = context.getStringAttribute("resultSetType");
        ResultSetType resultSetTypeEnum = resolveResultSetType(resultSetType);
        if (resultSetTypeEnum == null) {
          resultSetTypeEnum = configuration.getDefaultResultSetType();
        }
        String keyProperty = context.getStringAttribute("keyProperty");
        String keyColumn = context.getStringAttribute("keyColumn");
        String resultSets = context.getStringAttribute("resultSets");
    
       //将上面获取到的属性,封装成MappedStatement对象,我们解析mappper.xml中的非常重要的类
        builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
            fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
            resultSetTypeEnum, flushCache, useCache, resultOrdered,
            keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets);
      }
    
    include标签

    这个具体的sql解析的SqlSource ,单独放一篇文章总结,方便自己好看,现在只看下SqlSource的debug调试的结果,可以看到具体的sql以及参数


    image.png
    • 封装成MappedStatement对象的代码

    一个MappedStatement就是一个sql,整个项目中有很多sql,是存在Configuration中的mappedStatements 这个参数里面的,她是一个StrictMap


    image.png
      protected final Map<String, MappedStatement> mappedStatements = new StrictMap<MappedStatement>("Mapped Statements collection")
          .conflictMessageProducer((savedValue, targetValue) ->
              ". please check " + savedValue.getResource() + " and " + targetValue.getResource());
    
     public MappedStatement addMappedStatement(
          String id,
          SqlSource sqlSource,
          StatementType statementType,
          SqlCommandType sqlCommandType,
          Integer fetchSize,
          Integer timeout,
          String parameterMap,
          Class<?> parameterType,
          String resultMap,
          Class<?> resultType,
          ResultSetType resultSetType,
          boolean flushCache,
          boolean useCache,
          boolean resultOrdered,
          KeyGenerator keyGenerator,
          String keyProperty,
          String keyColumn,
          String databaseId,
          LanguageDriver lang,
          String resultSets) {
    
        if (unresolvedCacheRef) {
          throw new IncompleteElementException("Cache-ref not yet resolved");
        }
    
        id = applyCurrentNamespace(id, false);
        boolean isSelect = sqlCommandType == SqlCommandType.SELECT;
    
       //利用构造者模式进行MappedStatement
        MappedStatement.Builder statementBuilder = new MappedStatement.Builder(configuration, id, sqlSource, sqlCommandType)
            .resource(resource)
            .fetchSize(fetchSize)
            .timeout(timeout)
            .statementType(statementType)
            .keyGenerator(keyGenerator)
            .keyProperty(keyProperty)
            .keyColumn(keyColumn)
            .databaseId(databaseId)
            .lang(lang)
            .resultOrdered(resultOrdered)
            .resultSets(resultSets)
            .resultMaps(getStatementResultMaps(resultMap, resultType, id))
            .resultSetType(resultSetType)
            .flushCacheRequired(valueOrDefault(flushCache, !isSelect))
            .useCache(valueOrDefault(useCache, isSelect))
            .cache(currentCache);
    
        ParameterMap statementParameterMap = getStatementParameterMap(parameterMap, parameterType, id);
        if (statementParameterMap != null) {
          statementBuilder.parameterMap(statementParameterMap);
        }
    
        MappedStatement statement = statementBuilder.build();
        configuration.addMappedStatement(statement);
        return statement;
      }
    
    

    至此MyBatis的查询前构建的过程大致这样子,简单地说就是
    ①MyBatis会在执行查询之前,对配置文件进行解析成配置对象:Configuration
    ②存放SQL的xml又会解析成MappedStatement对象,但是MappedStatement最后还是放入到Configuration中的一个集合中的
    所以最终我们需要操作的对象就是Configuration


    image.png image.png

    相关文章

      网友评论

          本文标题:从Java原生的Jdbc操作数据库到MyBatis 1

          本文链接:https://www.haomeiwen.com/subject/zwfurrtx.html