MyBatis 學習記錄1 一個簡單的demo

 

主題

  最近(N個月前)clone了mybatis的源碼..感受相比於spring真的很是小...而後看了看代碼以爲寫得很精簡...感受個人寫代碼思路和這個框架比較類似(很難具體描述...就是相對來講比較容易理解做者想幹嗎,雖然也沒有註釋..)...因此打算好好研究學習下.java

 

從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 }

這段代碼的輸出以下:mysql

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大體看了看都作了哪些事情.spring

 

初始化SqlSessionFactory時候各類對象之間的關係

SqlSessionFactory通常一個應用只會建立1個.在程序初始化的時候建立.從這個對象中能夠獲取SqlSession,SqlSession是Facade設計模式.SqlSession能夠獲取Mapper.獲取了Mapper就能夠進行各類查詢了.sql

要建立SqlSessionFactory能夠經過SqlSessionFactoryBuilder的build方法來建立,build能夠有不少可選的參數,好比inputstram,file...等等..最終都是轉化成configuration.apache

轉化成configuration的時候也須要藉助於XMLConfigBuilder的parse方法.設計模式

對象之間關係大體如圖:緩存

1.咱們須要的是SqlSession.咱們通常和它打交道.從它裏面能夠獲取Mappersession

2.SqlSession須要經過SqlSessionFactory來建立.mybatis

3.SqlSessionFactory須要經過SqlSessionFactoryBuilder來build.同時build的時候須要一份配置,這個配置就是Configuration,而Configuration對象須要使用XMLConfigBuilder來解析XML生成app

同時須要指定使用配置中的哪一個環境?由於一個配置能夠有多個環境,區別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能夠共享二級緩存.

 

 

 以上就是初始化階段對象之間的一些關係對的簡單梳理

相關文章
相關標籤/搜索