我想从数据库获取值,在我的情况下,我使用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,PROVIDER_CODE order by CLIENT,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()); }
解决方法
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] }
相关链接