強(qiáng)大:MyBatis 流式查詢
MyBatis 提供了一個(gè)叫 org.apache.ibatis.cursor.Cursor 的接口類用于流式查詢,這個(gè)接口繼承了 java.io.Closeable 和 java.lang.Iterable 接口,由此可知:Cursor 是可關(guān)閉的; Cursor 是可遍歷的。
isOpen():用于在取數(shù)據(jù)之前判斷 Cursor 對(duì)象是否是打開(kāi)狀態(tài)。只有當(dāng)打開(kāi)時(shí) Cursor 才能取數(shù)據(jù);isConsumed():用于判斷查詢結(jié)果是否全部取完。getCurrentIndex():返回已經(jīng)獲取了多少條數(shù)據(jù)
cursor.forEach(rowObject -> {...});但構(gòu)建 Cursor 的過(guò)程不簡(jiǎn)單
@Mapper
public interface FooMapper {
@Select("select * from foo limit #{limit}")
Cursor<Foo> scan(@Param("limit") int limit);
}MyBatis 就知道這個(gè)查詢方法一個(gè)流式查詢。@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
}
}java.lang.IllegalStateException: A Cursor is already closed.方案一:SqlSessionFactory
@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 處我們開(kāi)啟了一個(gè) SqlSession (實(shí)際上也代表了一個(gè)數(shù)據(jù)庫(kù)連接),并保證它最后能關(guān)閉;2 處我們使用 SqlSession 來(lái)獲得 Mapper 對(duì)象。這樣才能保證得到的 Cursor 對(duì)象是打開(kāi)狀態(tài)的。
方案二:TransactionTemplate
在 Spring 中,我們可以用 TransactionTemplate 來(lái)執(zhí)行一個(gè)數(shù)據(jù)庫(kù)事務(wù),這個(gè)過(guò)程中數(shù)據(jù)庫(kù)連接同樣是打開(kāi)的。代碼如下:
@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;
});
}方案三:@Transactional 注解
@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 注解。這個(gè)方案看上去最簡(jiǎn)潔,但請(qǐng)注意 Spring 框架當(dāng)中注解使用的坑:只在外部調(diào)用時(shí)生效。在當(dāng)前類中調(diào)用這個(gè)方法,依舊會(huì)報(bào)錯(cuò)。關(guān)注公眾號(hào)【Java技術(shù)江湖】后回復(fù)“PDF”即可領(lǐng)取200+頁(yè)的《Java工程師面試指南》
強(qiáng)烈推薦,幾乎涵蓋所有Java工程師必知必會(huì)的知識(shí)點(diǎn),不管是復(fù)習(xí)還是面試,都很實(shí)用。

評(píng)論
圖片
表情
