一尘不染

[Ljava.lang.Object; 无法投射到

hibernate

我想从数据库中获取价值,就我而言,我曾经List从数据库中获取价值,但是却遇到了这个错误

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to id.co.bni.switcherservice.model.SwitcherServiceSource
at id.co.bni.switcherservice.controller.SwitcherServiceController.LoadData(SwitcherServiceController.java:48)
at id.co.bni.switcherservice.controller.SwitcherServiceController.main(SwitcherServiceController.java:62)

这是我的代码

    Query LoadSource = session_source.createQuery("select CLIENT,SERVICE,SERVICE_TYPE,PROVIDER_CODE,COUNT(*) FROM SwitcherServiceSource" +
            " where TIMESTAMP between :awal and :akhir" +
            " and PROVIDER_CODE is not null group by CLIENT,SERVICE,SERVICE_TYPE,PROVIDER_CODE order by CLIENT,SERVICE,SERVICE_TYPE,PROVIDER_CODE");
    LoadSource.setParameter("awal", fromDate);
    LoadSource.setParameter("akhir", toDate);

    List<SwitcherServiceSource> result_source = (List<SwitcherServiceSource>) LoadSource.list();
    for(SwitcherServiceSource tes : result_source){
        System.out.println(tes.getSERVICE());
    }

任何帮助将是荣幸:)

@raffian,你的意思是这样吗?

List<Switcher> result = (List<Switcher>) LoadSource.list();
for(Switcher tes : result){
    System.out.println(tes.getSERVICE());
}

阅读 269

收藏
2020-06-20

共1个答案

一尘不染

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to id.co.bni.switcherservice.model.SwitcherServiceSource

问题是

(List<SwitcherServiceSource>) LoadSource.list();

这将返回一个 对象数组 列表 (Object []),
其中包含SwitcherServiceSource表中每一列的标量值。Hibernate将使用ResultSetMetadata推断返回的标量值的实际顺序和类型。

List<Object> result = (List<Object>) LoadSource.list(); 
Iterator itr = result.iterator();
while(itr.hasNext()){
   Object[] obj = (Object[]) itr.next();
   //now you have one array of Object for each row
   String client = String.valueOf(obj[0]); // don't know the type of column CLIENT assuming String 
   Integer service = Integer.parseInt(String.valueOf(obj[1])); //SERVICE assumed as int
   //same way for all obj[2], obj[3], obj[4]
}

相关连结

2020-06-20