【发布时间】:2012-03-31 10:48:49
【问题描述】:
我在我的项目中使用 Spring 和 Hibernate。在 DAO 实现 java 文件中编写了许多方法,每个方法都使用相同的 try/catch/finally 代码行,这对我来说似乎是多余的。
我被告知要优化/重构代码,因为文件 LOC 超过 10k。我在某处读到使用 HibernateDaoSupport 我们不必担心异常或关闭会话。它将由 Spring 自己处理。
有人可以帮助我如何继续或做必要的或更好的方法来处理异常吗?我在下面粘贴了 DAO 层中一种方法的代码。
公共类 CSDDaoImpl 扩展 HibernateDaoSupport 实现 CSDDao {
public Deal getDealStructure(long dealId) throws CSDServiceException {
Session session = null;
try {
session = getSession();
Deal deal = (Deal) session.createCriteria(Deal.class).add(
Restrictions.eq("dealId", dealId)).uniqueResult();
return deal;
} catch (DataAccessResourceFailureException darfex) {
String message = "Failed to retrieve the deal object.";
CSDServiceException ex = new CSDServiceException(message, darfex);
ex.setStackTrace(darfex.getStackTrace());
ex.setErrorCode(Constants.DATA_ACCESS_FAILURE_EXP);
ex.setMessageToUser(message);
throw ex;
} catch (IllegalStateException isex) {
String message = "Failed to retrieve the deal object.";
CSDServiceException ex = new CSDServiceException(message, isex);
ex.setStackTrace(isex.getStackTrace());
ex.setErrorCode(Constants.ILLEGAL_STATE_EP);
ex.setMessageToUser(message);
throw ex;
} catch (HibernateException hbex) {
String message = "Failed to retrieve the deal object.";
CSDServiceException ex = new CSDServiceException(message, hbex);
ex.setStackTrace(hbex.getStackTrace());
ex.setErrorCode(Constants.HIBERNATE_EXP);
ex.setMessageToUser(message);
throw ex;
} finally {
if (session != null && session.isOpen()) {
try {
session.close();
} catch (HibernateException hbex) {
log.error("Failed to close the Hibernate Session.", hbex);
hbex.printStackTrace();
CSDServiceException ex = new CSDServiceException(
"Failed to close the Hibernate Session.", hbex);
ex.initCause(hbex.getCause());
ex.setStackTrace(hbex.getStackTrace());
throw ex;
}
}
}
}
}
【问题讨论】:
标签: spring hibernate exception-handling