SqlSessionFactoryBuilder source Mybatis analysis of the source code analysis

A, Mybatis environment Getting Started

1, maven dependence

<dependencies>
    <!-- mybatis核心包 -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.3.0</version>
    </dependency>
    <!-- mysql驱动包 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.29</version>
    </dependency>
    <!-- junit测试包 -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
    </dependency>
</dependencies>

2. Create a profile configuration mybatis

<? xml Version = "1.0" encoding = "UTF-8"?> 
<! DOCTYPE the Configuration 
        the PUBLIC "- // mybatis.org//DTD Config 3.0 // EN" 
        "http://mybatis.org/dtd/mybatis config.dtd--3 "> 
<configuration> 
    <-! environment configuration -> 
    <environments default =" Development "> 
        <environment ID =" Development "> 
            <the transactionManager type =" the JDBC "/> 
            <-! database connection configuration, dynamically acquires the content file config.properties here -> 
            <type the dataSource = "the POOLED"> 
                <Property name = "Driver" value = "com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/test"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <!-- mapping文件路径配置 -->
    <mappers>
        <mapper resource="mapper/UserMapper.xml"/>
    </mappers>

</configuration>

3, Mapper configuration file

<?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,namespace的值习惯上设置成包名+sql映射文件名,这样就能够保证namespace的值是唯一的
例如namespace="com.mayikt.mapper.UserMapper"就是com.mayikt.mapper(包名)+userMapper(userMapper.xml文件去除后缀)
 -->
<mapper namespace="com.mayikt.mapper.UserMapper">
    <!-- 在select标签中编写查询的SQL语句, 设置select标签的id属性为getUser,id属性值必须是唯一的,不能够重复
    使用parameterType属性指明查询时使用的参数类型,resultType属性指明查询返回的结果集类型
    resultType="com.mayikt.entity.User"就表示将查询结果封装成一个User类的对象返回
    User类就是users表所对应的实体类
    -->
    <!--
        根据id查询得到一个user对象
     -->
    <select id="getUser" parameterType="int"
            resultType="com.mayikt.entity.UserEntity">
        select * from user where id=#{id}
    </select>
</mapper>

4、实体类

public class UserEntity {
    private Integer id;
    private Date birdate;
    private String name;
}

5、mapper接口

public interface UserMapper {
    public UserEntity getUser(int id);
}

6、运行Mybatis代码

public class TestMyBatis {

    public static void main(String[] args) {
        try {
            //配置文件
            String configXml = "mybatis_config.xml";
            //加载配置获取流
            Reader reader = Resources.getResourceAsReader(configXml);
            //获取sqlSessionFactory工厂
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            //获取sqlSession
            SqlSession sqlSession = sqlSessionFactory.openSession();
            //获取对应的mapper
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            //执行方法
            UserEntity user = userMapper.getUser(1);
            System.out.println("name:" + user.getName());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

7、数据表结构

CREATE TABLE `user` (
  `id` int(11) NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

二、Mybatis核心配置文件

1、Properties(属性)

    Java属性文件可以配置直观的。

如:

<properties>
        <property name="jdbc.driver" value="com.mysql.jdbc.Driver"/>
        <property name="jdbc.url" value="jdbc:mysql:///mybatis"/>
        <property name="jdbc.username" value="root"/>
        <property name="jdbc.password" value="root"/>
</properties>

或者通过直接引入属性文件,例如:

<properties resource="db.properties"></properties>

然后db.properties文件中的配置就是:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///mybatis
jdbc.username=root
jdbc.password=root

2、typeAliases(类型别名)

类型别名是Java类型的简称。

逐个设置,例如:

<typeAliases>

   <typeAlias type="com.mayikt.entity.User" alias="user"/>

</typeAliases>

3、Plugins

分页插件配置

四、Mybatis大体架构流程分析

1、流程图

      1、读取resources获取对应的Reader对象。

            reader = Resources.getResourceAsReader(resources);

       2、使用SqlSessionFactoryBuilder获取SqlSessionFactory源码分析

           SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader); 

源码分析:

1.进入到build 传递reader有参数构造函数

最终就执行

  1. SqlSessionFactoryBuilder使用XMLConfigBuilder解析配置文件,封装成Configuration对象。

 

注意:XMLConfigBuilder运行之后,只能被解析一次 否则会抛出异常。

xml转换程bean对象 configuration

XMLConfigBuilder的作用是:解析mybatis配置文件文件 得到configuration

XMLMapperBuilder的作用是什么: 解析mybatisMapper文件

建议很多源码中设置值都是采用构造函数形式

loadedResource 存放都是mybatis映射的文件路由地址 使用set集合存放

1.protected final Set<String> loadedResources = new HashSet<String>();

注意:mapper文件配置的namespace一定要和接口对应 否则情况查找失败!

2mapperRegistry作用存放dao层mapper接口 底层使用过map集合存放。。

 

  1. 将配置文件中的mappers注册到configuration的mapperRegistry中

 

所以在configuration中的 mapperRegistry注册mapperRegistry接口。

  2、使用configuration获取默认的DefaultSqlSessionFactory

五、MybatisMapper接口绑定原理

  1. Reader reader = Resources.getResourceAsReader(resources);

       调用javaioAPI  读取resources配置文件,获取InputStreamReader

     2、SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);

  3、使用XMLConfigBuilder 解析mybatis配置文件

4、因为在构造函数设置了parsed 为fasle,XMLConfigBuilder 只能被使用一次。

调用该方法解析mybatis_config文件

通过反射机制匹配接口

 

解析配置文件完成了之后,都会装配到configuration

Configuration作用:mybatis核心的配置文件内容 ,使用xml转换bean

Mybatis扫包方式有两种一种是 写package、和resource

 

明白了 mapperRegistry 注册我们的Mapper文件。

 六、总结:

  1. 获取本地InputStreamReader对象(mybatis配置文件)
  2. 调用SqlSessionFactoryBuilder 
  3. ###在使用XMLConfigBuilder解析mybatis配置文件,装配到Configuration中。
  4. 将配置文件中的Mapper添加到Configuration mapperRegistry实现注册。

        备注:mapperRegistry存放当前所有的mapper文件。

       5.使用Configuration获取默认的DefaultSqlSessionFactory

 

Guess you like

Origin www.cnblogs.com/cxyyh/p/11080646.html