简体   繁体   中英

How to add named query result to a class in java

I have a named query which results into a list of lists. I am trying to store that data into a class(dto), while doing that i am getting an exception "[err] java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to java.util.List". below is the code i am using

public List<CapFutureFteForecastDto> getresults() {
    List<resultsDto> resultListDto = new ArrayList<>();
    Query query = getSession().getNamedQuery("getresults");
    List<List<Object>> result = query.list();
    List<Float> monthsDataList = new ArrayList<>();
    for(int i=0; i<result.size();i++){
        List<Object> result1 = (List<Object>) result.get(i);
        for(int index = 1; index < result1.size(); index++){
            monthsDataList.add((Float)(result1.get(index)));
        }
    resultListDto.get(i).setName((String)result1.get(0));
    resultListDto.get(i).setMonthsData(monthsDataList);
    result1.clear();
    monthsDataList.clear();
    }
    return resultListDto;
}

And my class is:

public class resultsDto {

    private String name;

    private List<Float> monthsData ;
    
    public List<Float> getMonthsData() {
        return monthsData;
    }

    public void setMonthsData(List<Float> monthsData) {
        this.monthsData = monthsData;
    }
    
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

The result of named query is having 3 rows as follows:

[xyz,1,24.5,1.2]
[abc,2.5,3,4]
[qwe,3,4.2,5]

I am getting " java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to java.util.List" exception at

List<Object> result1 = (List<Object>) result.get(i);

not sure where i am doing wrong. can you please tell me what is the issue with the above code.

Thanks in advance.

result.get(i) is an array of object (not a list), you need to declare it this way:

Object[] result1 = (Object[]) result.get(i);

You also need to change the type of result :

List<Object[]> result = query.list();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM