最後にこれを解決できました。他人を助けるコードスニペットの共有
これはスレッドレベルでのトランザクションを維持することで実現できます。しかし、これらすべてのスレッド間で共有オブジェクトが必要になります。この共有オブジェクトは、すべてのスレッドのステータスを追跡し、どちらかが失敗した場合に通知します。このスレッドによって障害通知が受信されると、スレッド自体が例外をスローし、トランザクションがロールバックされます。共有クラス内の個々のスレッドで
例コードコードが
@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を使用してデータを保存している場合はここで失敗条件があります。それ以外の場合はすべて成功します
バッチ処理されていないデータを保存する場合は、SessionFactoryの代わりにStatelessSessionを使用します.StatuselessSessionがメモリを過負荷にしない主な理由、Hibernateの仕組みを理解する必要があります。 –