以下内容对我有用:
数据源配置.java
@Bean
public LocalSessionFactoryBean sessionFactory() {
// Link your data source to your session factory
...
}
@Bean("hibernateTxManager")
public HibernateTransactionManager hibernateTxManager(@Qualifier("sessionFactory") SessionFactory sessionFactory) {
// Link your session factory to your transaction manager
...
}
MyServiceImpl.java
@Service
@Transactional(propagation = Propagation.REQUIRES_NEW, transactionManager = "hibernateTxManager", readOnly = true)
public class MyServiceImpl implements MyService {
@Autowired
private MyRepo myRepo;
...
Stream<MyEntity> stream = myRepo.getStream();
// Do your streaming and CLOSE the steam afterwards
...
MyRepoImpl.java
@Repository
@Transactional(propagation = Propagation.MANDATORY, transactionManager = "hibernateTxManager", readOnly = true)
public class MyRepoImpl implements MyRepo {
@Autowired
private SessionFactory sessionFactory;
@Autowired
private MyDataSource myDataSource;
public Stream<MyEntity> getStream() {
return sessionFactory.openStatelessSession(DataSourceUtils.getConnection(myDataSource))
.createNativeQuery("my_query", MyEntity.class)
.setReadOnly(true)
.setFetchSize(1000)
.stream();
}
...
请记住,当您进行流式传输时,您实际上只需要在对象具体化点对内存保持谨慎。这确实是操作中唯一容易出现内存问题的部分。在我的例子中,我一次将流切块为1000个对象,使用gson序列化它们并立即将它们发送到JMS代理。垃圾回收器完成其余的工作。
值得注意的是,Spring的交易边界感知在最后关闭了与dB的连接,而不需要明确告知。