1

我有一个列表,我需要对其进行迭代,即使在使用 Iterator 或 for 循环之后,它也会给我类转换异常,给我的问题是

代码如下,

List<DataLoaderIndex> dataList = new ArrayList<DataLoaderIndex>();

dataList = dataLoaderIndexDAO.getDataSourceStatus(uploadFrequency,reportEndDate);

Map<String,String> mapData = new HashMap<String,String>();

Iterator<DataLoaderIndex> itrObj = dataList.iterator();
            while (itrObj.hasNext()) {
                DataLoaderIndex dlObj = itrObj.next();
                String dsName = dlObj.getDataSourceType();
                    String dsStatus = dlObj.getStatus();
                    mapData.put(dsName, dsStatus);

            }

/*for(int i=0;i<dataList.size();i++){
             String dsName = dataList.get(i).getDataSourceType();
             String dsStatus = dataList.get(i).getStatus();
             mapData.put(dsName, dsStatus);
         }*/

DAO 部分在这里:

public List<DataLoaderIndex> getDataSourceStatus(String uploadFrequency,String reportEndDate){


    List<DataLoaderIndex> dataList = null;
    if(session!=null){
        Query query = session.createQuery("select dataSourceType,uploadedBy,status from DataLoaderIndex where DATE (reportEndDate) =:endate and UPPER(reportFreq) = UPPER(:uploadFreq)");  
        query.setString("endate", reportDate);
        query.setString("uploadFreq", uploadFrequency);
        dataList = query.list();
    }

    return dataList;
}

我得到了这条线的例外

String dsName = dlObj.getDataSourceType(); 

...

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.work.in.synct.entity.DataLoaderIndex
    at com.work.synct.service.dataloaderimpl.DataUploadDetailsService.getUploadStatus(DataUploadDetailsService.java:36)
4

1 回答 1

0

在该DAO方法中,查询应该使用强类型TypedQuery。由于此时未键入查询,因此它返回一个List<Object[]>可以分配给dataList由于类型擦除的查询。在运行时List<DataLoaderIndex>会丢失其类型信息,因此可以为其分配List<Object[]>.

List<DataLoaderIndex> dataList = null;
if(session!=null){
    TypedQuery<DataLoaderIndex> query = session.createQuery("select dataSourceType," +
        "uploadedBy,status from DataLoaderIndex where DATE " +
           " (reportEndDate) =:endate and UPPER(reportFreq) = UPPER(:uploadFreq)", 
              DataLoaderIndex.class);


    query.setString("endate", reportDate);
    query.setString("uploadFreq", uploadFrequency);
    dataList = query.list();
}

return dataList;

更新

我刚刚意识到你没有使用 JPA。而是尝试在 DAO 方法中转换返回的列表。在某些时候,您需要向上转换为类型List<DataLoaderList>

dataList = (List<DataLoaderList>)query.list();

于 2013-09-03T09:33:47.483 回答