mybatis如何對大量數(shù)據(jù)的游標查詢
mybatis對大量數(shù)據(jù)的游標查詢
mapper定義
@Mapper
public interface NewsRepository {
String simpleQuery="select news.id,news.title,news.keywords," +
" news.url,news.author," +
" data.content,news.inputtime,news.updatetime " +
" from news news join news_data data on news.id=data.id";
/**
* 使用游標查詢數(shù)據(jù)數(shù)據(jù)
* @return
*/
@Select(value = simpleQuery +
" where status=1" +
" order by news.id asc")
@Options(fetchSize = Integer.MIN_VALUE)//mysql情況比較特殊,只能這樣設置
Cursor<News> scrollResult();
}service內(nèi)使用
Cursor<News> cursor= repository.scrollResult();
Iterator<News> iter= cursor.iterator();
int count=0;
while (iter.hasNext()){
System.err.println(iter.next().title);
..........
}mybatis游標查詢 org.apache.ibatis.cursor.Cursor
先說使用場景:針對超大數(shù)據(jù),內(nèi)存不夠存儲數(shù)據(jù)。
假設有一個1千萬的日志數(shù)據(jù),需要將這一千萬的數(shù)據(jù),全部都清洗一遍,從每一條的數(shù)據(jù)中查詢出匹配的有效數(shù)據(jù),且不能修改原始數(shù)據(jù)。
第一種辦法
一次性查出來,內(nèi)存不夠,而且會很慢,不可取。
這種方法就直接放棄。
第二種辦法
分頁查詢, 每次查詢1000條,每次處理完后,再分頁查詢。
這種分頁查詢,分頁會很慢,除非是有索引id,通過順序讀取,還有可以優(yōu)化一下。
第三種辦法
游標查詢 org.apache.ibatis.cursor.Cursor
數(shù)據(jù)庫查詢DAO
TempStudent 數(shù)據(jù)POJO
@Select(" SELECT * FROM temp_student ")
Cursor<TempStudent> findListForCursor();查詢的service
@Transactional
public void scanTempStudent() {
Cursor<TempStudent> cursor = tempStudentDao.findListForCursor();
cursor.forEach(foo -> {
System.out.println(foo.getId() + ":" + foo.getName());
});
}特別注意,需要加上一個注解 Transactional, 事物的注解
為什么呢?
在取數(shù)據(jù)的過程中需要保持數(shù)據(jù)庫連接,而 Mapper 方法通常在執(zhí)行完后連接就關閉了,因此 Cusor 也一并關閉了,所以加上了事物保障就可以
Spring 框架當中注解使用的坑:只在外部調(diào)用時生效。在當前類中調(diào)用這個方法,依舊會報錯。
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Spring Security 密碼驗證動態(tài)加鹽的驗證處理方法
小編最近在改造項目,需要將gateway整合security在一起進行認證和鑒權(quán),今天小編給大家分享Spring Security 密碼驗證動態(tài)加鹽的驗證處理方法,感興趣的朋友一起看看吧2021-06-06

