zoukankan      html  css  js  c++  java
  • MyBatis 学习记录1 一个简单的demo

     

    主题

      最近(N个月前)clone了mybatis的源码..感觉相比于spring真的非常小...然后看了看代码觉得写得很精简...感觉我的写代码思路和这个框架比较相似(很难具体描述...就是相对来说比较容易理解作者想干嘛,虽然也没有注释..)...所以打算好好研究学习下.

    从1个简单的DEMO来入门

     1 package test.test;
     2 
     3 import org.apache.ibatis.session.SqlSession;
     4 import org.apache.ibatis.session.SqlSessionFactory;
     5 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
     6 import test.mapper.UserMapper;
     7 import test.model.User;
     8 
     9 import java.io.FileInputStream;
    10 import java.io.IOException;
    11 import java.io.InputStream;
    12 
    13 public class MyTest {
    14     public static void main(String[] args) throws IOException {
    15         String resource = "mybatis-config.xml";
    16         InputStream inputStream = new FileInputStream(resource);
    17         //从 XML 中构建 SqlSessionFactory
    18         SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    19         SqlSession session = sqlSessionFactory.openSession();
    20         try {
    21             UserMapper mapper = session.getMapper(UserMapper.class);
    22             User u = mapper.selectByPrimaryKey(1);
    23             System.out.println(u);
    24 
    25             User u2 = mapper.selectByPrimaryKey(1);
    26             System.out.println(u2);
    27         } finally {
    28             session.close();
    29         }
    30     }
    31 }

    这段代码的输出如下:

    Connected to the target VM, address: '127.0.0.1:51496', transport: 'socket'
    2018-09-24 10:13:47,501 DEBUG [main] logging.LogFactory : Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
    Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
    PooledDataSource forcefully closed/removed all connections.
    PooledDataSource forcefully closed/removed all connections.
    PooledDataSource forcefully closed/removed all connections.
    PooledDataSource forcefully closed/removed all connections.
    Opening JDBC Connection
    Mon Sep 24 10:13:47 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
    Created connection 13928019.
    Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@d48653]
    ==>  Preparing: select id, user_id, user_name, real_name, email, creator_uid, modifier_uid, created_at, updated_at, del from user where id = ? and del = 0 
    ==> Parameters: 1(Integer)
    <==    Columns: id, user_id, user_name, real_name, email, creator_uid, modifier_uid, created_at, updated_at, del
    <==        Row: 1, 1, test, realName, jyzjyz12@163.com, 1, 1, 2018-09-24 10:10:43.0, 2018-09-24 10:10:46.0, 0
    <==      Total: 1
    User{id=1, userId=1, userName='test', realName='realName', email='jyzjyz12@163.com', creatorUid=1, modifierUid=1, createdAt=Mon Sep 24 10:10:43 CST 2018, updatedAt=Mon Sep 24 10:10:46 CST 2018, del=false}
    User{id=1, userId=1, userName='test', realName='realName', email='jyzjyz12@163.com', creatorUid=1, modifierUid=1, createdAt=Mon Sep 24 10:10:43 CST 2018, updatedAt=Mon Sep 24 10:10:46 CST 2018, del=false}
    Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@d48653]
    Disconnected from the target VM, address: '127.0.0.1:51496', transport: 'socket'
    Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@d48653]
    Returned connection 13928019 to pool.

    就几行代码.我就debug大致看了看都做了哪些事情.

    初始化SqlSessionFactory时候各种对象之间的关系

    SqlSessionFactory一般一个应用只会创建1个.在程序初始化的时候创建.从这个对象中可以获取SqlSession,SqlSession是Facade设计模式.SqlSession可以获取Mapper.获取了Mapper就可以进行各种查询了.

    要创建SqlSessionFactory可以通过SqlSessionFactoryBuilder的build方法来创建,build可以有很多可选的参数,比如inputstram,file...等等..最终都是转化成configuration.

    转化成configuration的时候也需要借助于XMLConfigBuilder的parse方法.

    对象之间关系大致如图:

    1.我们需要的是SqlSession.我们一般和它打交道.从它里面可以获取Mapper

    2.SqlSession需要通过SqlSessionFactory来创建.

    3.SqlSessionFactory需要通过SqlSessionFactoryBuilder来build.同时build的时候需要一份配置,这个配置就是Configuration,而Configuration对象需要使用XMLConfigBuilder来解析XML生成

    同时需要指定使用配置中的哪个环境?因为一个配置可以有多个环境,区别qa,dev,prod....等等.还可以传入参数,因为配置URL,USERNAME,PASSWORD的时候可以传入占位符.

    4.创建好SqlSessionFactory以后我们就可以通过openSession方法来获取SqlSession了.SqlSession要执行SQL或者给你Mapper.需要用到executor来真正执行SQL,executor要执行SQL肯定也需要用到TransactionFactory创建的Transaction,Transaction对象要能正确执行事务,肯定需要用到Datasource,事务隔离级别level,是否autoCommit等参数.这些参数可以在Configuration(Environment)里获取

    5.executor是装饰着的设计模式.默认返回的是CacheExecutor内部装饰着SimpleExecutor.SimpleExecutor中存在着mybatis的一级缓存,从我们的打印日志中可以看出来.我们SQL只打印了一次.所以同一个Mapper多次查询同样的SQL是有一级缓存的.如果你换了一个SqlSession,那就无效了.所以一级缓存是在SqlSession级别的.而二级缓存在CacheExecutor中.不同的SqlSession可以共享二级缓存.

     以上就是初始化阶段对象之间的一些关系对的简单梳理

  • 相关阅读:
    C#进行Visio二次开发之设备状态跟踪
    C#进行Visio二次开发之Shape的Data1、Data2、Data3的用处
    C#进行Visio二次开发之界面设计及架构设计
    Sqlserver常用函数例子说明
    香港生肖采集及规则分析软件
    使用NVelocity0.5实现服务器端页面自动生成
    C#进行Visio二次开发之判断图纸是否有设备
    C#进行Visio二次开发之图纸缩放操作的实现
    C#进行Visio开发的事件处理
    导线应力及弧垂计算相关资料
  • 原文地址:https://www.cnblogs.com/abcwt112/p/9695039.html
Copyright © 2011-2022 走看看