我的 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 控制台中检查此选择命令时,它返回正确的值。那么我做错了什么?
最佳答案
看看this other question 。
uniqueResult
方法至少返回一个 Number
,然后尝试以下操作:
long rowCount = ((Number)cr.uniqueResult()).longValue();
return (rowCount > 0) ? true : false;
关于java - 如何正确检查数据库中是否存在行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13068706/