spring - 使用 JTA 批量插入(EntityManager 不能使用 getTransaction)

标签 spring apache-camel spring-data batch-processing entitymanager

我在一个使用 spring data 和 apache camel 的项目中工作,我们有 2 个数据库,Sql Server 和带有 JTA 的 Oracle。出现问题是因为我需要从一个大文件(大约 10000000 条记录)中插入数据,所以我决定使用批量插入作为:

@PersistenceContext(unitName="persistenceUnitSql")
EntityManager em;

public void insertBatch() {
    em.getTransaction().begin();
    for (int i = 1; i <= 1000000; i++) {
      Point point = new Point(i, i);
      em.persist(point);
      if ((i % 10000) == 0) {
          em.getTransaction().commit();
          em.clear();          
          em.getTransaction().begin();
      }
    }
    em.getTransaction().commit();
}

但是这个问题发生了:

    A JTA EntityManager cannot use getTransaction()

任何帮助...

最佳答案

self 控制JTA事务似乎比想象的要难得多。我通常使用的一种解决方法是有一个单独的“服务”来执行一批插入,并且您在该方法上设置 REQUIRES_NEW 事务传播策略,所以它看起来像:

class FooService {

    private PointPersister pointPersister;

    @Transactional(propagation=REQUIRED)
    public void insertBatch() {
        List<Point> points = new ArrayList<Point>(10000);
        for (int i = 1; i <= 1000000; i++) {
            points.add(new Point(i,1));
            if ((i % 10000) == 0) {
                pointPersister.insertPointBatch(points);
            }
        }
    }
}

class PointPersisterImpl implements PointPersister {
    @PersistenceContext
    private EntityManager em;

    @Transactional(propagation=REQUIRES_NEW)    // in a separate txn
    public void insertPointBatch(List<Point> points) {
        // persist points
    }
}

您还可以做出其他选择,以避免处理麻烦且容易出错的手动事务处理。 Spring Batch是可能的解决方案之一。

关于spring - 使用 JTA 批量插入(EntityManager 不能使用 getTransaction),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19964977/

相关文章:

java - 将gzip添加到spring嵌入式tomcat中

java - 二级缓存永不命中using、spring3、hibernate4、ehcache?

java - Camel Route无限运行以移动JMS消息

spring - 放松 Spring Data REST 投影的安全性

java - 在 hibernate 中添加一个懒惰的 child

java - 对远程 Web 服务的 Spring Boot http 调用

spring - org.springframework.web.client.ResourceAccessException : I/O error on GET request for in Microservices

java - Apache Camel : multicast with aggregation - AggregationStrategy called too often

c - Apache Camel 和 C 的架构建议

java - Spring Data JPA - 将@Query 与多对多关系/连接表结合使用