给你个实例来看下好处, 比如 我们处理业务请求的时候, 都是需要事物来控制提交和回滚的, 是不是每次都需要重复的写 try catch 来begin和commit 或者rollback呢
定义一个你需要的接口来规范行为: 无需对它做实现类.public interface TransactionAction {
void execute(ActionEvent event) throws Exception;
}
定义这个规范, 也就是成功提交 失败回滚
public void transactionProcess(TransactionAction action, ActionEvent event)
throws Exception {
UserTransaction ut = null;
try {
ut = Trans.getUserTransaction();
ut.begin();
action.execute(event);
ut.commit();
} catch (Exception ex) {
StringWriter aWriter = new StringWriter();
ex.printStackTrace(new PrintWriter(aWriter));
Log.error(this.getClass(), aWriter.toString());
try {
ut.rollback();
} catch (Exception e) {
throw new SysException(DAOErrorType.DAO_ROLLBACK_ERROR, e);
}
if (ex instanceof NoMessageAppException) {
return;
}
if (ex instanceof PopupAppException || ex instanceof AppException) {
throw ex;
}
AppException appException = new AppException(-1, ex);
if (null != ex.getMessage()) {
appException.setLocalizedErrorMessage(ex.getMessage());
} else {
appException.setLocalizedErrorMessage(StringResource.getStringData(
"MSG_GS_SP_02143", JSFHelper.getRequest()));
}
throw appException;
}
}
业务中使用:
public void next(ActionEvent event) throws Exception {
helper.transactionProcess(new TransactionAction() {
public void execute(ActionEvent event) throws Exception {
//这时候你只需要关注你的业务了, 不需要管事物了.
}
}
}
ActionEvent: 这个参数就是你业务对象了, 如一般BaseFormBean.
2013年1月04日 14:24