java.lang.ClassCastException:java.lang.Class无法强制转换为java.lang.String

时间:2016-11-02 15:21:11

标签: java

我在jpa maven项目中使用JPQL的stats方法,我在客户端项目中测试时遇到了这个错误。

  

java.lang.ClassCastException:java.lang.Class无法强制转换为java.lang.String

public int StatDoctorBySpeciality()
 {

    int  count = 0 ;
    Query query = em.createQuery("SELECT  COUNT(u)  FROM User AS u where u.role like 'doctor'  GROUP BY u.specialite ");

    List<Object[]> results = query.getResultList();

        for (int i = 0; i < results.size(); i++) {
             Object[] arr =(Object[]) results.get(i);
            for (int j = 0; j < arr.length; j++) {
                System.out.print(arr[j] + " ");
                count= (int) arr[j] ;

            }
            }
        return count;
}

1 个答案:

答案 0 :(得分:0)

最后这是一个强制转换异常,因为getResultList()只返回List <Long>而不是List<Long[]>

  

Ljava.lang.Long是java.lang.Longs的列表

public int StatDoctorBySpeciality() {
       int count =0;
    List<Long> results = em
            .createQuery("SELECT  COUNT(u)  FROM User AS u where u.role like 'doctor'  GROUP BY u.specialite").getResultList();
    for (Long result : results) {

         count = ((Number) result).intValue();
    }  
    return count ;
}