【发布时间】:2020-06-17 04:00:54
【问题描述】:
我的 Dao 类中有以下方法
public Collection<Files> findFilesByFolder(Collection<Integer> ids) {
if (ids.size() > 0) {
StringBuffer qbe = new StringBuffer("select f from Files f where f.folders.idFolders in ( :id )");
return super.list(qbe, "id", ids);
}
else {
return new ArrayList<Files>(0);
}
}
当我调用这个函数时,它返回 java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.lang.Integer exception
这是 list() 的声明。我希望 hibernate 正在处理集合。但不知道这如何以类强制转换异常告终。谢谢
protected Collection<T> list(StringBuffer qbe, Object... parameterMap) throws InfrastructureException {
return this.findByQuery(qbe.toString(), parameterMap);
}
@SuppressWarnings("unchecked")
public Collection<T> findByQuery(String qbe, Object... parameterMap) throws InfrastructureException {
return (Collection<T>) anonymousFindByQuery(qbe, parameterMap);
}
-------------------------------------------------------------------------------------------
public Collection<?> anonymousFindByQuery(String qbe, Object ...parameterMap)
throws InfrastructureException{
getSession();
try {
Query q = createQuery(qbe, parameterMap);
return q.list();
} //end try
catch (HibernateException ex) {
WLog.DAOLogger.error("HibernateException", ex);
throw new InfrastructureException(ex);
} //end
}
--------------------------------------------------------------------------------------
protected Query createQuery(String qbe, Object... parameterMap) throws InfrastructureException {
Session session = getSession();
Query q = session.createQuery(qbe);
String formattedQuery = String.format("%s ", qbe);
for (int i = 0; i < parameterMap.length; i = i + 2) {
//Put the data in easy to use forms.
Object key = parameterMap[i];
Object value = parameterMap[i + 1];
String formattedKey = String.format(":%s ", key);
if(value == null || formattedQuery.indexOf(formattedKey) == -1){
continue;
}
if(value instanceof ArrayList){
q.setParameterList(key.toString(), (Collection<?>)value);
}
else{
q.setParameter(key.toString(), value);
}
}
return q;
}
【问题讨论】:
-
哪一行代码产生了错误信息?
-
@Kenster return super.list(qbe, "id", ids); 返回错误。
-
不确定是不是这样,但你给的是
Collection<Integer>,但请检查它是否是instanceof ArrayList。并非每个集合都是ArrayList,它也可以是 LinkedList,因此不会触发该条件。
标签: java dao classcastexception