• 使用Mybatis的Cursor
  • 代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import org.apache.ibatis.cursor.Cursor;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.StreamSupport;

@Service
public class DemoService {

@Autowired
private DemoMapper demoMapper;
@Autowired
private SqlSessionFactory sqlSessionFactory;
@Resource
PlatformTransactionManager platformTransactionManager;

public List<Demo> getDataFromMysql() {

List<Demo> demos = new ArrayList<>();

//第一种方式(sqlseesion方式)
SqlSession sqlSession = sqlSessionFactory.openSession(); // 1
try (Cursor<Demo> cursor = sqlSession.getMapper(DemoMapper.class).getDataFromMysql(2);){
StreamSupport.stream(cursor.spliterator(), true).forEach(
demo -> {
demos.add(demo);
}
);
} catch (Exception e) {
throw new RuntimeException(e);
}

////第二种方式(spring事务管理器方式)
//TransactionTemplate transactionTemplate = new TransactionTemplate(platformTransactionManager);
//transactionTemplate.execute(status -> { // 2
// try (Cursor<Demo> cursor = demoMapper.getDataFromMysql(2)) {
// StreamSupport.stream(cursor.spliterator(), true).forEach(
// demo -> {
// demos.add(demo);
// }
// );
// } catch (IOException e) {
// e.printStackTrace();
// }
// return null;
//});
//
////第三种 @Transactional(此方法加上@Transactional)
//try (Cursor<Demo> cursor = demoMapper.getDataFromMysql(2)) {
// StreamSupport.stream(cursor.spliterator(), true).forEach(
// demo -> {
// demos.add(demo);
// }
// );
//} catch (IOException e) {
// e.printStackTrace();
//}

return demos;
}
}