java - spring 数据如何清理事务方法中的持久化实体?

标签 java spring hibernate spring-data transactional

我需要通过 hibernate 使用 spring 数据接收和保存大量数据。我们的服务器分配的 RAM 不足以同时保存所有实体。我们肯定会得到 OutOfMemory 错误。

所以我们显然需要批量保存数据。此外,我们还需要使用 @Transactional 来确保即使出现单个错误,所有数据是否持久化。

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

那么,使用 Spring Data 处理大量数据的最佳方法是什么?也许 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 而不是为了获得高性能。因此,如果您不关心性能,您可以安全地使用此策略。

关于java - spring 数据如何清理事务方法中的持久化实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54147047/

相关文章:

java - 在 Canvas 上及时移动点,Android 中的速度(java)

java - 在 android studio 中使用 2D 数组

java - Spring Boot 测试数据库初始化运行两次

java - Hibernate 标准如何不加载子进程

java - 对称密码学解密问题

java - 如何在集群中维护 session 或变量状态或对象状态(特别是基于 Java 的应用程序服务器)?

java - 如何为 <form :select> from controller using properties file? 分配选项值

javascript - Angular 2 : TypeScript/Javascript: Converting JSON string value to proper JSON object

java - 在 Spring 中解析 Multipart/mixed

hibernate - OSGi + hibernate