文档章节

Mybatis执行流程(一)

wjk_snail
 wjk_snail
发布于 2016/06/22 18:11
字数 857
阅读 88
收藏 1

##搭建一个简单的Mybatis+Maven项目 ###Maven依赖

  <!-- 添加log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>
        <!-- 添加mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.6</version>
        </dependency>
        <!-- 添加mysql驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.12</version>
        </dependency>
        <!-- 添加junit驱动 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.14.8</version>
        </dependency>

###代码


@Data
public class Student {
    private Long id;
    private String name;
}

public interface StudentDao {
        public void insert(Student student);
        public Student findUserById (int id);
        public List<Student> findAllUsers();
}

public class StudentDaoTest {
    @Test
    public void findUserById() {
        SqlSession sqlSession = getSessionFactory().openSession();
        StudentDao userMapper = sqlSession.getMapper(StudentDao.class);
        Student user = userMapper.findUserById(1);
        System.out.println(user.toString());
    }

    //Mybatis 通过SqlSessionFactory获取SqlSession, 然后才能通过SqlSession与数据库进行交互
    private static SqlSessionFactory getSessionFactory() {
        SqlSessionFactory sessionFactory = null;
        String resource = "configuration.xml";
        try {
            sessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader(resource));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sessionFactory;
    }
}

###配置文件

//configuration.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>

    <!-- 指定properties配置文件, 我这里面配置的是数据库相关 -->
    <properties resource="dbConfig.properties"></properties>
    <!-- 指定Mybatis使用log4j -->
    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/student"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <!-- 映射文件,mybatis精髓, 后面才会细讲 -->
    <mappers>
        <mapper resource="userDao-mapping.xml"/>
    </mappers>
</configuration>
//userDao-mapping.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
        "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
<mapper namespace="com.mybatis.StudentDao">
    <select id="findUserById" resultType="com.mybatis.Student" >
        select * from student where id = #{id}
    </select>
</mapper>	

##通过SqlSessionFactory获取SqlSession ###执行流程图 ###源码走读 ####获取reader

sessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader(resource));
Resources.getResourceAsReader(resource)

####获取SqlSessionFactory #####build()方法

//调用SqlSessionFactoryBuilder.build()方法获取SqlSessionFactory
public SqlSessionFactory build(Reader reader, String environment, Properties properties) { 
		//获取解析器
 		XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
 		//解析配置文件
      return build(parser.parse());
}

#####解析配置返回configuration

	//XMLConfigBuilder.parse()解析配置返回configuration
	public Configuration parse() {
    if (parsed) {
      throw new BuilderException("Each XMLConfigBuilder can only be used once.");
    }
    parsed = true;
    //configuration为根节点
    parseConfiguration(parser.evalNode("/configuration"));
    //解析完成后返回configration
    return configuration;
  }

  private void parseConfiguration(XNode root) {
  	//接下来有10个子节点,注意在configuration.xml中配置子节点的时候得按照解析的顺序
  	//这些节点的解析后面的博客再走读
    try {
      propertiesElement(root.evalNode("properties")); //issue #117 read properties first
      typeAliasesElement(root.evalNode("typeAliases"));
      pluginElement(root.evalNode("plugins"));
      objectFactoryElement(root.evalNode("objectFactory"));
      objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
      settingsElement(root.evalNode("settings"));
      environmentsElement(root.evalNode("environments")); // read it after objectFactory and objectWrapperFactory issue #631
      databaseIdProviderElement(root.evalNode("databaseIdProvider"));
      typeHandlerElement(root.evalNode("typeHandlers"));
      mapperElement(root.evalNode("mappers"));
    } catch (Exception e) {
      throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
    }
  }

#####获得SqlSessionFactory

  //通过configuration获得SqlSessionFactory
  public SqlSessionFactory build(Configuration config) {
    return new DefaultSqlSessionFactory(config);
  }

####获取sqlSession #####调用openSession()方法

//调用SqlSessionFactory的openSession()方法
public SqlSession openSession() {
	//主要看看这个方法
    return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
}

######获取SqlSession

//通过DefaultSqlSessionFactoryz获取SqlSession
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
    Transaction tx = null;
    try {
      //Environment子节点获得数据连接的配置还有事务的配置
      final Environment environment = configuration.getEnvironment();
      final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
      tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
      //获取执行器
      final Executor executor = configuration.newExecutor(tx, execType);
      return new DefaultSqlSession(configuration, executor, autoCommit);
    } catch (Exception e) {
      closeTransaction(tx); // may have fetched a connection so lets call close()
      throw ExceptionFactory.wrapException("Error opening session.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }

######获取Executor

  //Configurationz中获取执行器(Executor)
  public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
    executorType = executorType == null ? defaultExecutorType : executorType;
    executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
    Executor executor;
    if (ExecutorType.BATCH == executorType) {
      executor = new BatchExecutor(this, transaction);
    } else if (ExecutorType.REUSE == executorType) {
      executor = new ReuseExecutor(this, transaction);
    } else {
      executor = new SimpleExecutor(this, transaction);
    }
    //缓存配置,如下
    /* 
    	<select id="findUserById"  useCache="true" resultType="com.mybatis.Student">
        select * from student where id = #{id}
    	</select>
	 /*
    if (cacheEnabled) {
      executor = new CachingExecutor(executor);
    }
    //执行拦截器 其实就是plugins子节的配置
    executor = (Executor) interceptorChain.pluginAll(executor);
    return executor;
  }

通过上面的操作变获得有含有confingration,Executor,transaction,数据库连接等的sqlsession。

参考:http://www.cnblogs.com/dongying/p/4142476.html

© 著作权归作者所有

共有 人打赏支持
wjk_snail
粉丝 7
博文 70
码字总数 50704
作品 0
东城
MyBatis初探一

一、MyBatis介绍 mybatis(持久层框架3.2.6 or 3.2.7)简单执行流程 >1.SqlMapConfig.xml(全局配置文件),配置数据源,事务和运行环境等 >2.配置映射文件(编写SQL语句):mapper.xml... >3.SqlSes...

AAASSSSddd
2016/04/02
64
0
Mybatis入门(一)

MyBatis的前身叫iBatis,本是apache的一个开源项目, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis。MyBatis是支持普通SQL查询,存储过程和高级映射的...

Heinrich_Chen
2016/01/07
91
0
深入浅出MyBatis_Index

深入浅出MyBatis系列 【深入浅出MyBatis系列一】MyBatis入门 【深入浅出MyBatis系列二】配置简介(MyBatis源码篇) 【深入浅出MyBatis系列三】Mapper映射文件配置 【深入浅出MyBatis系列四】...

陶邦仁
2015/12/22
932
0
mybatis功能架构及执行流程

一、功能架构设计 功能架构讲解: 我们把Mybatis的功能架构分为三层: (1)API接口层:提供给外部使用的接口API,开发人员通过这些本地API来操纵数据库。接口层一接收到调用请求就会调用数据处...

J星星点灯
2017/12/20
0
0
存储过程-数据库

一、存储过程 存储过程主要包括以下元素:1.变量的声明和初始化;2.SQL语句;3.流程控制关键字(if.....else....);4.关键字。 一个简单的例子: @num,为int类型,需要用户在执行该存储过程时...

小车车
2016/08/27
16
0

没有更多内容

加载失败,请刷新页面

加载更多

记Structured Streaming 2.3.1的OOM排查过程

记Structured Streaming 2.3.1的OOM排查过程 缘起 最近在使用Structured Streaming开发一套自助配置SQL的来生成流式作业的平台,在测试的过程中发现有些作业长时间运行后会有Executor端的OOM...

纳兰清风
12分钟前
0
0
通过 websocket 连接 openfire

通过 websocket 连接 openfire 一、简介 老版本是需要安装websocket插件的。之前版本就不说了。 二、 引入XML与JSON互转的js <script src="lib/XML/ObjTree.js"></script><script src="lib......

lwenhao
16分钟前
0
0
MicropPython的学习,如何从0到1?

是Java还是C++ ? 是Go还是Python? 你为你最爱或者最熟悉的编程语言打Call了吗? Python在国外是一门非常热门的编程语言,近些年在国内也被发掘与追捧, Python的开放、简洁、黏合正符合了现发...

bodasisiter
17分钟前
0
0
Django框架17: Celery的使用

Celery介绍 1.什么是Celery Celery是一个python模块,它在官网的定义:Celery is asynchronous task queue/job based on distributed message passing. It is focused on real-time operatio......

代码打碟手
23分钟前
0
0
poi的excel解析工具类

import org.apache.commons.lang.StringUtils;import org.apache.commons.lang.time.DateFormatUtils;import org.apache.commons.lang.time.DateUtils;import org.apache.poi.hssf.use......

Sheav
27分钟前
0
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部