加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

java-Spring数据如何清除事务方法中的永久实体?

发布时间:2020-12-15 01:17:34 所属栏目:大数据 来源:网络整理
导读:我需要在休眠状态下使用spring数据接收并保存大量数据.我们的服务器分配的RAM不足,无法同时保留所有实体.我们肯定会得到OutOfMemory错误. 因此,我们需要分批保存数据,这很明显.同样,我们需要使用@Transactional来确保所有数据持久化或非持久化,即使出现单个

我需要在休眠状态下使用spring数据接收并保存大量数据.我们的服务器分配的RAM不足,无法同时保留所有实体.我们肯定会得到OutOfMemory错误.

因此,我们需要分批保存数据,这很明显.同样,我们需要使用@Transactional来确保所有数据持久化或非持久化,即使出现单个错误也是如此.

因此,问题是:@Transactional方法期间的spring数据是否将实体存储在RAM中或被刷新的实体可被垃圾收集器访问?

那么,用spring数据处理海量数据的最佳方法是什么?春季数据可能不是解决此类问题的正确方法.

最佳答案

Does spring data during @Transactional method keep storing entities in
RAM or entities which were flushed are accessible to garbage
collector?

实体将继续存储在RAM中(即,在entityManager中),直到清除事务提交/回滚或entityManager.这意味着只有在事务提交/回滚或
调用entityManager.clear().

So,what is the best approach to process huge mount of data with
spring data?

防止OOM的一般策略是逐批加载和处理数据.在每个批次的末尾,您应该刷新并清除entityManager,以便entityManager可以释放其用于CG的托管实体.常规代码流应如下所示:

@Component
public class BatchProcessor {

    //Spring will ensure this entityManager is the same as the one that start transaction due to  @Transactional
    @PersistenceContext
    private EntityManager em;

    @Autowired
    private FooRepository fooRepository;

    @Transactional
    public void startProcess(){

        processBatch(1,100);
        processBatch(101,200);
        processBatch(201,300);
        //blablabla

    }

    private void processBatch(int fromFooId,int toFooId){
        List<Foo> foos =  fooRepository.findFooIdBetween(fromFooId,toFooId);
        for(Foo foo :foos){
            //process a foo
        }

        /*****************************
        The reason to flush is send the update SQL to DB . 
        Otherwise,the update will lost if we clear the entity manager 
        afterward.
        ******************************/
        em.flush();
        em.clear();
    }
} 

请注意,此做法仅用于防止OOM,而不能用于实现高性能.因此,如果您不关心性能,则可以安全地使用此策略.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读