日期:2014-05-17  浏览次数:20660 次

通过hibernateTemplate.find().get(0)查询单个对象报错?
后台:
public AskleaveList query(String stuid,int contact){
      return (AskleaveList) hibernateTemplate.find("from Askleave a where a.stuid= '"+stuid+"' and a.contact = '"+contact+"'").get(0);
 }

运行时时报错:
java.lang.ClassCastException: com.model.Askleave cannot be cast to com.qihang.bgzdh.model.AskleaveList 
com.dao.impl.AskleaveDaoImpl.query(AskleaveDaoImpl.java:65)
显示上面的find方法执行出错
ssh

------解决方案--------------------
报错提示,hibernateTemplate.find("from Askleave a where a.stuid= '"+stuid+"' and a.contact = '"+contact+"'").get(0);返回的是Askleave类型,而你却转成AskleaveList。

还有你这种写法也不科学,你需要判断记录是否为空,如果为空的话,那么get(0)就会抛出异常。
public Askleave query(String stuid,int contact)
{
   List<Askleave> askleaveList =  hibernateTemplate.find("from Askleave a where a.stuid= '"+stuid+"' and a.contact = '"+contact+"'");
   if(askleaveList!= null && askleaveList.size()>0)
   {
   Askleave  askleave = askleaveList.get(0);
    return askleave ;
    }
   else  
    return null;
}

我不知道你代码里为什么要怎么写,建立AskleaveList这个对象,我觉得没必要。