[英]How to avoid automatic entity update on Hibernate ValidationException
我有一個spring
方法:我在構造對象之后驗證實體,這是先前從DB中獲取的。
@Transactional(rollbackFor={ValidationException.class})
public Object approve(Command command) throws ValidationException {
Object obj = merger.mergeWithExistingobject(command); // where I am fetching object from DB with old values and construct the new object
validatorService.validate( obj ); // which throws ValidationException
return saveObject(obj);
}
但不幸的是,甚至在拋出ValidationException
之后。 這些值仍然存在於DB中。 我怎樣才能避免這種情況。
您可以在ValidationException
上逐出該實體:
try {
validatorService.validate( obj );
} catch (ValidationException e) {
entityManager.detach(obj);
//Or with Hibernate API
//session.evict(obj);
throw e;
}
我從未使用過spring,但如果這與EJB相同,那么只有在拋出未經檢查的異常時才會回滾事務。
當從EJB方法拋出java.lang.Exception時,您顯然必須使用thethrows關鍵字在方法的簽名中聲明它。 在這種情況下發生的事情如下:1)事務被提交2)異常被重新拋給客戶端
取自此鏈接
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.