轉自:
http://www.java265.com/JavaFramework/MyBatis/202206/3614.html
下文筆者講述Mybatis流式查詢的相關簡介說明,如下所示
Mybatis流式查詢簡介
流式查詢簡介:
我們將MyBatis回傳資料為一個迭代器,這種查詢模式稱之為“流式查詢”
流式查詢的回傳值:
使用迭代器逐條的遍歷資料
流式查詢注意事項:
流式查詢程序中
資料庫連接必須保持一直打開
并且執行完查詢后需要手動的關閉資料庫連接
MyBatis流式查詢介面
MyBatis提供了 org.apache.ibatis.cursor.Cursor 的介面類用于流式查詢 此介面繼承了 java.io.Closeable 和 java.lang.Iterable 介面 所以Cursor 是可關閉/遍歷的,
Cursor常見的方法
| 方法名 | 備注 |
| isOpen() | 用于在取資料之前判斷 Cursor 物件是否是打開狀態,只有當打開時 Cursor 才能取資料 |
| isConsumed() | 用于判斷查詢結果是否全部取完 |
| getCurrentIndex() | 回傳已經獲取了多少條資料 |
使用 Cursor 流式介面
@Mapper
public interface TestMapper {
@Select("select * from test limit #{limit}")
Cursor<Test> scan(@Param("limit") int limit);
}
@GetMapping("test/1/{limit}")
public void testFun(@PathVariable("limit") int limit) throws Exception {
try (
SqlSession sqlSession = sqlSessionFactory.openSession(); // 1
Cursor<Test> cursor =
sqlSession.getMapper(TestMapper.class).scan(limit) // 2
) {
cursor.forEach(Test -> { });
}
}
上述代碼1位置
開啟一個SqlSession(實際上也代表了一個資料庫連接)
并保證它最后能關閉
2位置
使用 SqlSession 來獲得 Mapper 物件
采用以上模式能保證得到的 Cursor 物件是打開狀態的,
2.事務控制 TransactionTemplate
在 Spring 中,可以用 TransactionTemplate 來執行一個資料庫事務
@GetMapping("test/2/{limit}")
public void testFun(@PathVariable("limit") int limit) throws Exception {
TransactionTemplate transactionTemplate =
new TransactionTemplate(transactionManager); // 1
transactionTemplate.execute(status -> { // 2
try (Cursor<Test> cursor = TestMapper.scan(limit)) {
cursor.forEach(test -> { });
} catch (IOException e) {
e.printStackTrace();
}
return null;
});
}
上面的代碼中1處創建了一個 TransactionTemplate 物件
2處執行資料庫事務
而資料庫事務的內容則是呼叫Mapper物件的流式查詢
注意這里的 Mapper 物件無需通過 SqlSession 創建
事務控制 @Transactional 注解
這個本質上和方案二一樣,代碼如下:
@GetMapping("test/3/{limit}")
@Transactional
public void test(@PathVariable("limit") int limit) throws Exception {
try (Cursor<Test> cursor = TestMapper.scan(limit)) {
cursor.forEach(test -> { });
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/491883.html
標籤:Java
