Mybatis-解析過程

Mybatis核心類:
SqlSessionFactory:每個(gè)基于 MyBatis 的應(yīng)用都是以一個(gè) SqlSessionFactory 的實(shí)例為中心的。SqlSessionFactory 的實(shí)例可以通過 SqlSessionFactoryBuilder 獲得。而 SqlSessionFactoryBuilder 則可以從 XML 配置文件或通過Java的方式構(gòu)建出 SqlSessionFactory 的實(shí)例。SqlSessionFactory 一旦被創(chuàng)建就應(yīng)該在應(yīng)用的運(yùn)行期間一直存在,建議使用單例模式或者靜態(tài)單例模式彼哼。一個(gè)SqlSessionFactory對應(yīng)配置文件中的一個(gè)環(huán)境(environment),如果你要使用多個(gè)數(shù)據(jù)庫就配置多個(gè)環(huán)境分別對應(yīng)一個(gè)SqlSessionFactory。

SqlSession:SqlSession是一個(gè)接口沟优,它有2個(gè)實(shí)現(xiàn)類,分別是DefaultSqlSession(默認(rèn)使用)以及SqlSessionManager睬辐。SqlSession通過內(nèi)部存放的執(zhí)行器(Executor)來對數(shù)據(jù)進(jìn)行CRUD挠阁。此外SqlSession不是線程安全的,因?yàn)槊恳淮尾僮魍陻?shù)據(jù)庫后都要調(diào)用close對其進(jìn)行關(guān)閉溯饵,官方建議通過try-finally來保證總是關(guān)閉SqlSession侵俗。

Executor:Executor(執(zhí)行器)接口有兩個(gè)實(shí)現(xiàn)類,其中BaseExecutor有三個(gè)繼承類分別是BatchExecutor(重用語句并執(zhí)行批量更新)丰刊,ReuseExecutor(重用預(yù)處理語句prepared statements)隘谣,SimpleExecutor(普通的執(zhí)行器)。以上三個(gè)就是主要的Executor啄巧。通過下圖可以看到Mybatis在Executor的設(shè)計(jì)上面使用了裝飾者模式寻歧,我們可以用CachingExecutor來裝飾前面的三個(gè)執(zhí)行器目的就是用來實(shí)現(xiàn)緩存。


image.png

MappedStatement:MappedStatement就是用來存放我們SQL映射文件中的信息包括sql語句棵帽,輸入?yún)?shù)熄求,輸出參數(shù)等等。一個(gè)SQL節(jié)點(diǎn)對應(yīng)一個(gè)MappedStatement對象逗概。

解析過程

image.png

1 SqlSessionFactoryBuilder.build 創(chuàng)建DefaultSqlSessionFactory實(shí)體弟晚。
使用XMLConfigBuilder .parse()解析mybatis-config.xml, 生成Configuration對象(很重要的對象)

    public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
        SqlSessionFactory var5;
        try {
            XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
            var5 = this.build(parser.parse());
        } catch (Exception var14) {
            throw ExceptionFactory.wrapException("Error building SqlSession.", var14);
        } finally {
            ErrorContext.instance().reset();

            try {
                inputStream.close();
            } catch (IOException var13) {
            }

        }

        return var5;
    }

2 通過DefaultSqlSessionFactory.openSession創(chuàng)建DefaultSqlSession。
openSession->openSessionFromDataSource

   private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
       Transaction tx = null;

       DefaultSqlSession var8;
       try {
           Environment environment = this.configuration.getEnvironment();
           TransactionFactory transactionFactory = this.getTransactionFactoryFromEnvironment(environment);
           tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
           Executor executor = this.configuration.newExecutor(tx, execType);
           var8 = new DefaultSqlSession(this.configuration, executor, autoCommit);
       } catch (Exception var12) {
           this.closeTransaction(tx);
           throw ExceptionFactory.wrapException("Error opening session.  Cause: " + var12, var12);
       } finally {
           ErrorContext.instance().reset();
       }

       return var8;
   }

3 通過DefaultSqlSession拿到Mapper對象的代理MapperProxy.
mapperProxyFactory.newInstance(sqlSession)卿城,生成MapperProxyFactory代理對象

   public <T> T getMapper(Class<T> type) {
        return this.configuration.getMapper(type, this);
    }
    
        public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
        return this.mapperRegistry.getMapper(type, sqlSession);
    }
    
        public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
        MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory)this.knownMappers.get(type);
        if (mapperProxyFactory == null) {
            throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
        } else {
            try {
                return mapperProxyFactory.newInstance(sqlSession);
            } catch (Exception var5) {
                throw new BindingException("Error getting mapper instance. Cause: " + var5, var5);
            }
        }
    }
    
        public T newInstance(SqlSession sqlSession) {
        MapperProxy<T> mapperProxy = new MapperProxy(sqlSession, this.mapperInterface, this.methodCache);
        return this.newInstance(mapperProxy);
    }
    
        protected T newInstance(MapperProxy<T> mapperProxy) {
        return Proxy.newProxyInstance(this.mapperInterface.getClassLoader(), new Class[]{this.mapperInterface}, mapperProxy);
    }

4 通過MapperProxy調(diào)用Maper中相應(yīng)的方法
MapperProxy.invoke->MapperMethod.execute
先解析參數(shù)枚钓,在調(diào)sqlSession.insert執(zhí)行sql.

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        try {
            if (Object.class.equals(method.getDeclaringClass())) {
                return method.invoke(this, args);
            }

            if (this.isDefaultMethod(method)) {
                return this.invokeDefaultMethod(proxy, method, args);
            }
        } catch (Throwable var5) {
            throw ExceptionUtil.unwrapThrowable(var5);
        }

        MapperMethod mapperMethod = this.cachedMapperMethod(method);
        return mapperMethod.execute(this.sqlSession, args);
    }
// 產(chǎn)生MapperMethod ,這個(gè)對象很重要瑟押,是sql.xml生成的
    private MapperMethod cachedMapperMethod(Method method) {
        MapperMethod mapperMethod = (MapperMethod)this.methodCache.get(method);
        if (mapperMethod == null) {
            mapperMethod = new MapperMethod(this.mapperInterface, method, this.sqlSession.getConfiguration());
            this.methodCache.put(method, mapperMethod);
        }

        return mapperMethod;
    }

// 最終執(zhí)行sql地方
    public Object execute(SqlSession sqlSession, Object[] args) {
        Object param;
        Object result;
        switch(this.command.getType()) {
        case INSERT:
            param = this.method.convertArgsToSqlCommandParam(args);
            result = this.rowCountResult(sqlSession.insert(this.command.getName(), param));
            break;
        case UPDATE:
            param = this.method.convertArgsToSqlCommandParam(args);
            result = this.rowCountResult(sqlSession.update(this.command.getName(), param));
            break;
        case DELETE:
            param = this.method.convertArgsToSqlCommandParam(args);
            result = this.rowCountResult(sqlSession.delete(this.command.getName(), param));
            break;
        case SELECT:
            if (this.method.returnsVoid() && this.method.hasResultHandler()) {
                this.executeWithResultHandler(sqlSession, args);
                result = null;
            } else if (this.method.returnsMany()) {
                result = this.executeForMany(sqlSession, args);
            } else if (this.method.returnsMap()) {
                result = this.executeForMap(sqlSession, args);
            } else if (this.method.returnsCursor()) {
                result = this.executeForCursor(sqlSession, args);
            } else {
                param = this.method.convertArgsToSqlCommandParam(args);
                result = sqlSession.selectOne(this.command.getName(), param);
            }
            break;
        case FLUSH:
            result = sqlSession.flushStatements();
            break;
        default:
            throw new BindingException("Unknown execution method for: " + this.command.getName());
        }

        if (result == null && this.method.getReturnType().isPrimitive() && !this.method.returnsVoid()) {
            throw new BindingException("Mapper method '" + this.command.getName() + " attempted to return null from a method with a primitive return type (" + this.method.getReturnType() + ").");
        } else {
            return result;
        }
    }

5 DefaultSqlSession.update執(zhí)行sql
最終使用的是Executor執(zhí)行sql

    public int update(String statement, Object parameter) {
        int var4;
        try {
            this.dirty = true;
            MappedStatement ms = this.configuration.getMappedStatement(statement);
            var4 = this.executor.update(ms, this.wrapCollection(parameter));
        } catch (Exception var8) {
            throw ExceptionFactory.wrapException("Error updating database.  Cause: " + var8, var8);
        } finally {
            ErrorContext.instance().reset();
        }

        return var4;
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末搀捷,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子多望,更是在濱河造成了極大的恐慌嫩舟,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,755評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件怀偷,死亡現(xiàn)場離奇詭異家厌,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)椎工,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評論 3 395
  • 文/潘曉璐 我一進(jìn)店門饭于,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人维蒙,你說我怎么就攤上這事掰吕。” “怎么了颅痊?”我有些...
    開封第一講書人閱讀 165,138評論 0 355
  • 文/不壞的土叔 我叫張陵殖熟,是天一觀的道長。 經(jīng)常有香客問我八千,道長吗讶,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,791評論 1 295
  • 正文 為了忘掉前任恋捆,我火速辦了婚禮照皆,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘沸停。我一直安慰自己膜毁,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,794評論 6 392
  • 文/花漫 我一把揭開白布愤钾。 她就那樣靜靜地躺著瘟滨,像睡著了一般。 火紅的嫁衣襯著肌膚如雪能颁。 梳的紋絲不亂的頭發(fā)上杂瘸,一...
    開封第一講書人閱讀 51,631評論 1 305
  • 那天,我揣著相機(jī)與錄音伙菊,去河邊找鬼败玉。 笑死敌土,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的运翼。 我是一名探鬼主播返干,決...
    沈念sama閱讀 40,362評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼血淌!你這毒婦竟也來了矩欠?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,264評論 0 276
  • 序言:老撾萬榮一對情侶失蹤悠夯,失蹤者是張志新(化名)和其女友劉穎癌淮,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體沦补,經(jīng)...
    沈念sama閱讀 45,724評論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡该默,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了策彤。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,040評論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡匣摘,死狀恐怖店诗,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情音榜,我是刑警寧澤庞瘸,帶...
    沈念sama閱讀 35,742評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站赠叼,受9級特大地震影響擦囊,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜嘴办,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,364評論 3 330
  • 文/蒙蒙 一瞬场、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧涧郊,春花似錦贯被、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至批旺,卻和暖如春幌陕,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背汽煮。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評論 1 270
  • 我被黑心中介騙來泰國打工搏熄, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留棚唆,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,247評論 3 371
  • 正文 我出身青樓搬卒,卻偏偏與公主長得像瑟俭,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子契邀,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,979評論 2 355

推薦閱讀更多精彩內(nèi)容