[英]Using Play framework, persist Hibernate object after a database-related Exception
我是一個Play /休眠新手,試圖擴展我繼承的Play 1.2.3應用程序,該應用程序使用不可靠的數據解析文件的內容,並嘗試將其持久化到數據庫中。
當應用程序將其內容持久保存到數據庫時,我需要一種在數據庫中進行標記的方法。 在該應用程序尚未捕獲SQL異常之前,它就完全崩潰了。 因此,我將整個內容包裝在一個try-catch塊中,希望在catch塊中可以優雅地處理錯誤並在數據庫中記錄故障。
大致來說,這就是我將代碼更新為:
try {
MyObject parent = new MyObject();
// Persist the parent object and all of its child objects. The SQL errors are
// occurring on the child objects.
parent.save();
// Do a bit more processing
parent.status=1;
parent.save();
}
catch {
// This is what I'm trying to do -- set the failure status
// in the database to look at later
parent.status = 0;
parent.save();
}
MyObject繼承自:
package models;
import javax.persistence.*;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
@MappedSuperclass
public class MyObjectModel extends play.db.jpa.GenericModel { .. }
上面編寫的代碼拋出:
ERROR: current transaction is aborted, commands ignored until end of transaction block
ERROR ~ Could not synchronize database state with session
我嘗試在save()
parent.refresh()
之前調用parent.refresh()
,但結果是:
play.exceptions.JavaExecutionException: org.hibernate.exception.GenericJDBCException:
could not load an entity: [models.MyObject#465655]
我嘗試創建一個新的MyObject對象,並為其提供與上一個相同的值,包括先前獲取的Hibernate ID(並調用merge()
),但是結果是:
PersistenceException occured : org.hibernate.PersistentObjectException:
detached entity passed to persist: models.MyObject
如果我不給它以前獲取的Hibernate ID,它會拋出:
ERROR: current transaction is aborted, commands ignored until end of transaction block
PersistenceException occured : org.hibernate.exception.GenericJDBCException:
could not get next sequence value
我認為上述方法是最好的方法,因為那樣可以避免我級聯到所有我不想做的子對象(否則將再次失敗)。
查看文檔 ,我沒有主意。 希望有人可以幫助我! 我要做的只是向父對象(不是所有有問題的子對象)的數據庫行寫一個狀態代碼,以便可以在此處標記持久性失敗。
謝謝!
我猜想,當您遇到這樣的異常時,該事務將被標記為僅回滾(通過JPA.setRollbackOnly()
,而您所要做的就是提交當前事務並啟動一個新事務(通過JPAPlugin.closeTx
和startTx
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.