我正在使用JPA查询获取值,并在我尝试将实体转换为DTO时将结果放在List但服务类中。我收到错误“Ljava.lang.Object;无法转换为entityClass” ...我试过forloop,forEach循环和迭代器得到错误。当我尝试获取第一个元素并将其放入entityclass对象时,我得到了这个错误。
List<Dashboard> dashboard = (List<Dashboard>)dashboardRepository.findAll();
System.out.println("AllSolCount Length :------------------------------- "+dashboard.size());
List<DashboardDto> result = new ArrayList<DashboardDto>();
System.out.println("List Elements :----------------------------------- "+dashboard);
/*for(int i=0;i<dashboard.size();i++) {
**Dashboard obj = (Dashboard)dashboard.get(i); //error in this line I get**
DashboardDto dashboardDto = mapToDto(obj, DashboardDto.class, false);
result.add((DashboardDto) dashboardDto);
}
for (Dashboard obj : dashboard){
**DashboardDto dashboardDto = mapToDto(obj, DashboardDto.class, false);// error in this line I get**
result.add((DashboardDto) dashboardDto);
}*/
Iterator itr = dashboard.iterator();
while(itr.hasNext()){
**Dashboard obj = (Dashboard) itr.next(); // error here itself**
}
return result;
double *中的行是每个循环弹出错误的行。请提供建议
从DB中检索数据时,我正在返回实体类的列表,但不是实体类的列表,而是获取java对象的列表..所以我假设可能是某些配置或缺少某些东西..
对我来说是一个自定义查询 @Query(value =“SELECT sol.offering,sol.state,COUNT(sol.id)FROM Solution sol GROUP BY sol.offering,sol.state”) public List findAll();
答案 0 :(得分:1)
list()方法返回List
,你不能像你那样直接投射它们。
List<Dashboard> dashboard = (List<Dashboard>)dashboardRepository.findAll();
您必须存储在List<Object[]>
并逐个迭代List<Object[]>
,然后转换为List<Dashboard>
。
List<Object[]> list= (List<Object[]>)dashboardRepository.findAll();
List<Dashboard> mylist=new ArrayList<>();
if(list!=null){
for(Object [] ob:list){
member1=ob[0];
member2=ob[1];
.......
Dashboard db=new Dashboard(menber1,member2...);//or you use setter method for class member initialize.
mylist.add(db);
}
}