Join the Stack Overflow Community
Stack Overflow is a community of 6.8 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

i have stats method using JPQL in jpa maven project , i have got that error while testing in the client project.

java.lang.ClassCastException: java.lang.Class cannot be cast to 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;
}
share|improve this question
2  
arr[j].toString() – Compass Nov 2 '16 at 15:22
    
remove the + " " would work too System.out.print(arr[j]); , an exception is an object, so the toString() of Object will be call. PS : I don't see why you cast the get result since this is the type of your list. – AxelH Nov 2 '16 at 15:25
    
the return type is Int – hela Nov 2 '16 at 15:26
    
Wow, you use a lot of casting here then ... First, your exception say this is a Class type, not a String because it try to cast in String during the System.out.println() because you concat it with a String + " ". Then you will have an exception because you try to cast into int a Class instance – AxelH Nov 2 '16 at 15:28
    
the error persists even if i moved the System.out.println() and it still cannaot be casted to String while i don't even have a string now ! – hela Nov 2 '16 at 15:30
up vote 0 down vote accepted

Finally it was a casting exception because getResultList() returns just List <Long> instead of List<Long[]>

Ljava.lang.Long is a list of 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 ;
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.