gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 05:27:20 26 4
gpt4 key购买 nike

我在一个使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com