我们使用的是Apache的openJPA。我正在使用Java反射在托管bean中调用一个delete方法。当我试图删除由于违反约束而无法删除的托管对象时,就会出现问题。当我捕获InvocationTargetException并检索异常的原因时,它声明不存在要回滚的全局事务。
Caused by: java.lang.IllegalStateException: No Global Transaction exists to rollback.
at com.ibm.ws.tx.jta.UserTransactionImpl.rollback(UserTransactionImpl.java:349)
如果我进一步查看堆栈跟踪,我可以看到由于违反了约束而引发了SQL异常。
---- Begin backtrace for Nested Throwables
java.sql.SQLException: [SQL0532] Delete prevented by referential constraint CONSTRAINTNAME in LIBRARY.
有没有一种方法可以让我处理SQL异常,这样我就可以显示一条友好的消息,说明由于在另一个表中使用了删除操作,所以无法执行删除操作。
编辑-这是代码
public void deleteRowAction(Object list, DataTableTemplate template){
System.out.println("Delete Row");
try{
Object bean = getManagedBean(template.getDataManagerName());
Method methodDelete = getManagedBean(template.getDataManagerName()).getClass().getMethod(template.getDeleteMethod(),
Class.forName(template.getTableList_rowItemClassName()));
//Map<String, String[]> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterValuesMap();
methodDelete.invoke(bean, list);
}
catch(PersistenceException pe){
System.out.println("Persistence Exception Caught");
}
catch(NoSuchMethodException nsme){
nsme.printStackTrace();
}
catch(InvocationTargetException ite){
logException(ite);
FacesMessage message = new FacesMessage(ite.getCause().getMessage());
message.setSeverity(FacesMessage.SEVERITY_ERROR);
FacesContext context = this.getFacesContext();
context.addMessage(null, message);
}
catch(IllegalAccessException iae){
iae.printStackTrace();
}
catch(ClassNotFoundException cnfe){
cnfe.printStackTrace();
}
}
我们使用的是IBM的Websphere。以下代码由Websphere自动生成。由于数据限制,没有进行删除,因此回滚失败。这会导致回滚引发异常,从而导致原始异常丢失。如果我想看到Constraint异常(我们不能这样做),我必须修改这个方法。我们将记录一条通用错误消息。
@Action(Action.ACTION_TYPE.DELETE)
public String deleteVerificationDocumentCodeTable(
VerificationDocumentCodeTable verificationDocumentCodeTable)
throws Exception {
EntityManager em = getEntityManager();
try {
utx.begin();
em.joinTransaction();
verificationDocumentCodeTable = em
.merge(verificationDocumentCodeTable);
em.remove(verificationDocumentCodeTable);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception e) {
ex.printStackTrace();
throw e;
}
throw ex;
} finally {
em.close();
}
return "";
}
将异常传递到下面的方法,递归地检索SQLException
。
try{
....
} catch(PersistenceException pe){
SQLException sqle = translate(pe);
} catch(NoSuchMethodException nsme){
SQLException sqle = translate(nsme);
}
...
public SQLException translate(RuntimeException e) {
SQLException result = null;
Throwable throwable = e;
while (throwable != null && !(throwable instanceof SQLException)) {
throwable = throwable.getCause();
}
if (throwable instanceof SQLException) {
System.out.println("Found SQLException...")
result = (SQLException) throwable;
}
return result;
}