2012-10-25 82 views
1

我的一個DAO方法包含以下方法:如何正確檢查數據庫中是否存在行?

@Override 
public boolean isAvailable(String code) { 
    Criteria criteria = getSession().createCriteria(MyEntity.class); 
    cr.add(Restrictions.eq("code", code).ignoreCase()); 
    cr.setProjection(Projections.rowCount()); 
    Long rowCount = (Long) cr.uniqueResult(); 
    return (rowCount > 0) ? true : false; 
} 

在最後一行以下異常被拋出:

org.hibernate.exception.DataException: could not execute query 
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:102) 
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) 
at org.hibernate.loader.Loader.doList(Loader.java:2452) 
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2192) 
at org.hibernate.loader.Loader.list(Loader.java:2187) 
at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:119) 
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1706) 
at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:347) 
at org.hibernate.impl.CriteriaImpl.uniqueResult(CriteriaImpl.java:369) 

code在此表的主鍵。 Hibernate在控制檯中生成它的選擇命令。當我在我的數據庫的SQL控制檯中檢查這個select命令時,它會返回正確的值。那麼我做錯了什麼?

回答

0

解決我的問題是非常棘手的。上述問題中的參數code是解決問題的關鍵。在開始時,我在Hibernate實體類中有與此參數對應的列,定義爲具有5個符號長度的varchar。與此同時,我不得不改變它的長度只有2個標誌。但我正在調用5個字符串長度的方法。這就是我的錯誤發生的原因。我已經將varchar的長度再次改變爲5個符號,並且在這一刻中一切都可以。

1

this other questionuniqueResult返回至少Number的方法,那就試試這個:

long rowCount = ((Number)cr.uniqueResult()).longValue(); 
return (rowCount > 0) ? true : false; 
+0

我也簽出了這個:'對象rowCount = cr.uniqueResult();'和問題仍然是相同的。數字擴展對象,所以它應該工作,例外是相同的。 – woyaru

+0

那麼也許你的實體的類型映射有錯誤。也可能只有您的查詢返回的一些值(行)與您的映射類型不匹配。 – Esteve

相關問題