java.lang.IndexOutOfBoundsException: Index: 0, Size: 0我做了一个保存功能根据标题查询数据库是否有相同标题,有则更新没有则生成新纪录,但是若没有的话,查询就会造成空的list,报错代码如下public Plans findByPlanName(String planName) {


return (Plans)this.getSession().createQuery("from Plans where title=?").setParameter(0, planName).list().get(0) ; }如何避免查询数据库没有的纪录造成报错呢?

解决方案 »

  1.   

    换个写法,不要一下就返回了,总的判断结果是不是null吧,或者在其他地方调用的时候加判断
      

  2.   


    public Plans findByPlanName(String planName) {
           List<Plans> plansList = (List<Plans>) this.getSession().createQuery("from Plans where title=?").setParameter(0, planName).list();
           if (plansList.isEmpty())
               return null;
           return plansList.get(0) ;
    }
    然后在你调用的地方判断Plans是否为NULL,NULL则新增,否则更新
      

  3.   

    java.lang.IndexOutOfBoundsException: Index: 0, Size: 0这里的Size:0 是说list()方法返回的List<Plans>的长度为0,也就是说没有查到数据,而且如果你确定你查出来的结果只有1个的话,不要用list来查,可以这样写 Object obj = this.getSession().createQuery("from Plans where title=?").setParameter(0, planName).uniqueResult();
    if(obj!=null){
    return (Plans)obj;
    }else{
    //如果查询为记录,则做一些处理等等
    return null;
    }

    //这样也可以,但是return前还是最好判断一下
    Plans plans = (Plans)this.getSession().createQuery("from Plans where title=?").setParameter(0, planName).uniqueResult();
    return plans;