<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          還在擔心分頁慢嗎? MyBatis 流式查詢解決你的煩惱

          共 7508字,需瀏覽 16分鐘

           ·

          2021-07-29 23:30

          點擊上方 Java學習之道,選擇 設為星標

          每天18:30點,干貨準時奉上!

          來源: segmentfault.com/a/1190000022478915
          作者: 捏造的信仰

          Part1基本概念

          流式查詢指的是查詢成功后不是返回一個集合而是返回一個迭代器,應用每次從迭代器取一條查詢結(jié)果。流式查詢的好處是能夠降低內(nèi)存使用。

          如果沒有流式查詢,我們想要從數(shù)據(jù)庫取 1000 萬條記錄而又沒有足夠的內(nèi)存時,就不得不分頁查詢,而分頁查詢效率取決于表設計,如果設計的不好,就無法執(zhí)行高效的分頁查詢。因此流式查詢是一個數(shù)據(jù)庫訪問框架必須具備的功能。

          流式查詢的過程當中,數(shù)據(jù)庫連接是保持打開狀態(tài)的,因此要注意的是:執(zhí)行一個流式查詢后,數(shù)據(jù)庫訪問框架就不負責關(guān)閉數(shù)據(jù)庫連接了,需要應用在取完數(shù)據(jù)后自己關(guān)閉。

          Part2MyBatis 流式查詢接口

          MyBatis 提供了一個叫 org.apache.ibatis.cursor.Cursor 的接口類用于流式查詢,這個接口繼承了 java.io.Closeablejava.lang.Iterable 接口,由此可知:

          1. Cursor 是可關(guān)閉的。實際上當關(guān)閉 Cursor 時,也一并將數(shù)據(jù)庫連接關(guān)閉了;
          2. Cursor 是可遍歷的。

          除此之外,Cursor 還提供了三個方法:

          1. isOpen():用于在取數(shù)據(jù)之前判斷 Cursor 對象是否是打開狀態(tài)。只有當打開時 Cursor 才能取數(shù)據(jù);
          2. isConsumed():用于判斷查詢結(jié)果是否全部取完;
          3. getCurrentIndex():返回已經(jīng)獲取了多少條數(shù)據(jù)。

          因為 Cursor 實現(xiàn)了迭代器接口,因此在實際使用當中,從 Cursor 取數(shù)據(jù)非常簡單:

          try(Cursor cursor = mapper.querySomeData()) {
              cursor.forEach(rowObject -> {
                  // ...
              });
          }

          使用 try-resource 方式可以令 Cursor 自動關(guān)閉。

          Part3但構(gòu)建 Cursor 的過程不簡單

          我們舉個實際例子。下面是一個 Mapper 類:

          @Mapper
          public interface FooMapper {
              @Select("select * from foo limit #{limit}")
              Cursor<Foo> scan(@Param("limit") int limit);
          }

          方法 scan() 是一個非常簡單的查詢。我們在定義這個方時,指定返回值為 Cursor 類型,MyBatis 就明白這個查詢方法是一個流式查詢。

          然后我們再寫一個 SpringMVC Controller 方法來調(diào)用 Mapper(無關(guān)的代碼已經(jīng)省略):

          @GetMapping("foo/scan/0/{limit}")
          public void scanFoo0(@PathVariable("limit") int limit) throws Exception {
              try (Cursor<Foo> cursor = fooMapper.scan(limit)) {  // 1
                  cursor.forEach(foo -> {});                      // 2
              }
          }

          假設 fooMapper 是 @Autowired 進來的。注釋 1 處是獲取 Cursor 對象并保證它能最后關(guān)閉;2 處則是從 cursor 中取數(shù)據(jù)。

          上面的代碼看上去沒什么問題,但是執(zhí)行 scanFoo0(int) 時會報錯:

          java.lang.IllegalStateException: A Cursor is already closed.

          這是因為我們前面說了在取數(shù)據(jù)的過程中需要保持數(shù)據(jù)庫連接,而 Mapper 方法通常在執(zhí)行完后連接就關(guān)閉了,因此 Cusor 也一并關(guān)閉了。

          所以,解決這個問題的思路不復雜,保持數(shù)據(jù)庫連接打開即可。我們至少有三種方案可選。

          方案一:SqlSessionFactory

          我們可以用 SqlSessionFactory 來手工打開數(shù)據(jù)庫連接,將 Controller 方法修改如下:

          @GetMapping("foo/scan/1/{limit}")
          public void scanFoo1(@PathVariable("limit") int limit) throws Exception {
              try (
                  SqlSession sqlSession = sqlSessionFactory.openSession();  // 1
                  Cursor<Foo> cursor = 
                        sqlSession.getMapper(FooMapper.class).scan(limit)   // 2
              ) {
                  cursor.forEach(foo -> { });
              }
          }

          上面的代碼中,1 處我們開啟了一個 SqlSession (實際上也代表了一個數(shù)據(jù)庫連接),并保證它最后能關(guān)閉;2 處我們使用 SqlSession 來獲得 Mapper 對象。這樣才能保證得到的 Cursor 對象是打開狀態(tài)的。

          方案二:TransactionTemplate

          在 Spring 中,我們可以用 TransactionTemplate 來執(zhí)行一個數(shù)據(jù)庫事務,這個過程中數(shù)據(jù)庫連接同樣是打開的。代碼如下:

          @GetMapping("foo/scan/2/{limit}")
          public void scanFoo2(@PathVariable("limit") int limit) throws Exception {
              TransactionTemplate transactionTemplate = 
                      new TransactionTemplate(transactionManager);  // 1

              transactionTemplate.execute(status -> {               // 2
                  try (Cursor<Foo> cursor = fooMapper.scan(limit)) {
                      cursor.forEach(foo -> { });
                  } catch (IOException e) {
                      e.printStackTrace();
                  }
                  return null;
              });
          }

          上面的代碼中,1 處我們創(chuàng)建了一個 TransactionTemplate 對象(此處 transactionManager 是怎么來的不用多解釋,本文假設讀者對 Spring 數(shù)據(jù)庫事務的使用比較熟悉了),2 處執(zhí)行數(shù)據(jù)庫事務,而數(shù)據(jù)庫事務的內(nèi)容則是調(diào)用 Mapper 對象的流式查詢。注意這里的 Mapper 對象無需通過 SqlSession 創(chuàng)建。

          方案三:@Transactional 注解

          這個本質(zhì)上和方案二一樣,代碼如下:

          @GetMapping("foo/scan/3/{limit}")
          @Transactional
          public void scanFoo3(@PathVariable("limit") int limit) throws Exception {
              try (Cursor<Foo> cursor = fooMapper.scan(limit)) {
                  cursor.forEach(foo -> { });
              }
          }

          它僅僅是在原來方法上面加了個 @Transactional 注解。這個方案看上去最簡潔,但請注意 Spring 框架當中注解使用的坑:只在外部調(diào)用時生效。在當前類中調(diào)用這個方法,依舊會報錯。

          以上是三種實現(xiàn) MyBatis 流式查詢的方法。

          -- END --

           | 更多精彩文章 -



             
                    
          加我微信,交個朋友
                   
          長按/掃碼添加↑↑↑
                          

          瀏覽 29
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  豆花视频网站在线观看 | 波多野结衣AV在线播放 | 99看自拍 | 亚洲精品国产精品国自产网站 | 北条麻妃在线观看 |