我在 DB 表上有一個 Hibernate 偵聽器。當這個監聽器被觸發時,我想查詢另一個表并更新一些資料。但是,當我嘗試這樣做時,會收到如下錯誤:
org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:571)
...
Caused by: java.util.ConcurrentModificationException
at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1013)
我的代碼看起來像:
@Slf4j
@RequiredArgsConstructor
@Component
public class MyTableHibernateListener implements PostInsertEventListener, PreUpdateEventListener, PostUpdateEventListener {
private final JPQLQueryFactory queryFactory;
@Override
public boolean onPreUpdate(PreUpdateEvent event) {
try {
...
// Some working logic to set some data within the current MyTable.
// Try to query another table below
AnotherTable row = queryFactory.select(QAnotherTable.anotherTable)
.from(QAnotherTable.anotherTable)
.where(...)
.fetchOne();
...
log.info("Success");
return false;
} catch (Exception e) {
log.error("Failure", e);
throw e;
}
}
}
記錄了“成功”并且沒有記錄失敗,因此看起來錯誤發生在偵聽器方法之外。我還沒有在另一個表中進行任何資料庫更改,所以看起來甚至不允許查詢另一個表。有人可以幫助我了解這里可能存在什么問題以及推薦的解決方法可能是什么?
uj5u.com熱心網友回復:
您需要將查詢包裝在一個BeforeTransactionCompletionProcess(我假設您希望更新在同一事務中運行)并將其注冊到 Hibernate 操作佇列中。
@Override
public boolean onPreUpdate(PreUpdateEvent event) {
event.getSession().getActionQueue().registerProcess(new BeforeTransactionCompletionProcess() {
@Override
public void doBeforeTransactionCompletion(SessionImplementor session) {
//your query
}
});
...
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/521162.html
標籤:爪哇休眠jpa
