【问题标题】:Spring hibernate behaviour with multiple threads具有多个线程的 Spring 休眠行为
【发布时间】:2017-10-30 13:56:15
【问题描述】:

我有一个要求,其中需要大量的数据库操作。基本上它是支持 100 000 个数据操作的批量上传。我将文件分成块并将其提供给多个线程。我想要实现的是只有当所有线程都成功时,数据库操作才应该成功,否则它应该回滚整个操作。

我读过很多关于人们坚持不要在多线程中使用 spring hibernate 的文章。这是否可能使用spring SessionFactory,如果是的话,需要牢记哪些重要的东西。

【问题讨论】:

  • 如果你想保存非批处理数据,你应该去StatelessSession而不是SessionFactory,它的主要原因是StatelessSession不会超载你的内存,你必须了解Hibernate是如何工作的。

标签: spring multithreading hibernate


【解决方案1】:

终于可以解决这个问题了。分享代码 sn-p 可能会帮助其他人

这可以通过将事务保持在线程级别来实现。但是,您需要所有这些线程之间的共享对象。此共享对象将跟踪所有这些线程的状态,并在其中任何一个失败时通知它们。如果此线程收到失败通知,它们自己可以抛出异常,并且它们的事务将被回滚。

单个线程中的示例代码代码

    @Transactional(rollbackFor = Exception.class)
public void saveData(Product product, ProductStatusObject productStatusObject) throws Exception {
    productDao.persist(product);
    if(product.getId() == 5) {
        productStatusObject.updateCounter(false);
    } else {
        productStatusObject.updateCounter(true);
    }
    if(!productStatusObject.getStatus()) {
        throw new Exception();
    }
}

共享类中的代码

private final int totalThreads;

private int executedThreads = 0;
private Boolean finalStatus = true;

public ProductStatusObject(int totalThreads) {
    this.totalThreads = totalThreads;
}

public synchronized void updateCounter(Boolean threadStatus) throws InterruptedException {
    executedThreads ++;
    if(!threadStatus) {
        this.finalStatus = false;
    }
    if(totalThreads == executedThreads) {
        notifyAll();
    } else {
        wait();
    }

}

public synchronized Boolean getStatus() {
    return finalStatus;
}

这里的失败条件是如果任何线程正在保存 id 为 5 的数据,所有线程都将回滚它们的代码。否则一切都会成功

【讨论】:

    猜你喜欢
    • 2016-05-03
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    • 2012-05-05
    • 1970-01-01
    • 2015-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多