Hibernate中的java.lang.ClassCastException

时间:2013-01-05 09:43:02

标签: java hibernate java-ee exception object

我有两个表,如Doctorshift通过Hibernate查询语言我从fields表中选择两个Doctor,从Shift表中选择两个字段单个查询  所以我面临显示数据的问题。 我为bean写了一个DoctorShift calss,将列表转换为List<DoctorShift>我正在java.lang.ClassCastException那么该做什么 给出同样的想法......

code is like this

Query qry="-----";//valid query

List<DoctorShift> list=(List<DoctorShift>)qry.list();
System.out.println(" Size of list is "+list.size());// i'm getting 2

DoctorShift ds=list.get(0);// here i'm getting Exception




qry="select s.shiftNameId,s.shiftName,d.doctorRegnumvar,"
      +"d.doctorFnamevar,d.doctorLnamevar,d.doctorstatus," 
      +"sm.shiftstatus,s.shiftTime from ShiftDaoBean s,"
      + "DoctorDaoBean d,DoctorShiftMappingBean sm where "
      +"d.doctorid=sm.doctoridfk and  s.shiftID=sm.shiftidfk"
      +" and d.doctorid=:doctorID ";

帮帮我......

先谢谢

2 个答案:

答案 0 :(得分:0)

我认为你可以通过两种方式做你想做的事:

1)在DoctorShift类中创建构造函数,该构造函数接受所有必需的参数,并在您的HQL查询中使用此构造函数创建对象:

qry="select new com.yourpackage.DoctorShift(s.shiftNameId,s.shiftName,d.doctorRegnumvar,"
      +"d.doctorFnamevar,d.doctorLnamevar,d.doctorstatus," 
      +"sm.shiftstatus,s.shiftTime) from ShiftDaoBean s,"
      + "DoctorDaoBean d,DoctorShiftMappingBean sm where "
      +"d.doctorid=sm.doctoridfk and  s.shiftID=sm.shiftidfk"
      +" and d.doctorid=:doctorID ";

2)获取Object []数组列表,而不是DoctorShifts对象列表。每个数组都代表结果集中的行。例如:

Query qry="-----";//valid query

List<Object[]> list=(List<Object[]>)qry.list();
System.out.println(" Size of list is "+list.size());// i'm getting 2

Object[] firstRow =list.get(0);

System.out.println(firstRow[0]);// will output shiftNameId
System.out.println(firstRow[1]);// will output shiftName
...

在第二种情况下,您的查询仍然与您发布的相同。

答案 1 :(得分:0)

否则,您可以使用ResultTransformer在bean中加载数据。可以this blog帮助