[英]How to catch Hibernate SQL EXCEPTIONS IN SPRING
我正在使用hibernate在spring中執行sql語句但是為了處理異常我使用了hibernate異常和sql異常,但是我無法處理異常
如果我的SQL服務器沒有打開或無法訪問我無法捕獲異常我收到錯誤
org.hibernate.exception.JDBCConnectionException
這里是name.save(user);
是執行sql命令的hibernate命令
如何捕捉這種類型的例外
我收到了錯誤
JDBCConnectionException的無法訪問的catch塊。此異常永遠不會從try語句主體拋出
SQLException的無法訪問的catch塊。 永遠不會從try語句主體拋出此異常
mycode的:
try
{
ApplicationContext appContext =
new ClassPathXmlApplicationContext("/config/BeansInfo.xml");
TokenBo tokenBo = (TokenBo)appContext.getBean("TokenBo");
TokenModel token = new TokenModel();
token.setNumber(Number);
token.setID(ID);
}
catch(JDBCConnectionException ex )
{
System.out.println(ex);
}
catch(SQLException e){}
對於連接相關的異常使用JDBCConnectionException ,對於約束違例使用ConstraintViolationException 。 您應該根據您的要求使用其他例外。 請在此處輸入鏈接說明
除了@Tanjim Rahman之外,
代碼片段
在UserDAOImpl.java中
使用ConstraintViolationException捕獲重復的Entry
@Override
public String addUser(User user)
{
Session openSession = sessionFactory.openSession();
String retStr = null;
try
{
openSession.getTransaction().begin();
openSession.persist(user);
openSession.getTransaction().commit();
retStr = "success";
}
catch (ConstraintViolationException e)
{
openSession.getTransaction().rollback();
String[] tmpArr = e.getSQLException().toString().split(":");
String[] anotherTmpArr = null;
if( tmpArr.length > 1)
{
anotherTmpArr = tmpArr[1].split("for key");
}
retStr = anotherTmpArr[0];
}
catch (HibernateException e)
{
retStr = e.getLocalizedMessage();
}
finally
{
openSession.close();
}
return retStr;
}
您可能只捕獲直接拋出的異常(至少對於已檢查的異常...)。 如果你真的想以任何合理的方式處理這個特定的錯誤情況,有可能抓住你扔的東西並檢查提供的異常的原因
try {
// some hibernate calls
} catch (GenericJdbcException ge) {
if(ge.getCause() != null && ge.getCause() instanceof SQLException) {
SQLException se = (SQLException)ge.getCause();
if(se.getErrorCode() == -911) {
// your error handling for this case
}else{
throw ge; // do not swallow unhandled exceptions
}
}else{
throw ge // do not swallow unhandled exceptions
}
}
信任Oracle社區
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.