Shifat
Shifat

Reputation: 762

For Each Loop Not working

Here is my code -

    StringBuffer queryString = new StringBuffer();
    queryString.append("select m.user_message "); 
    queryString.append("from message m");
    Query query = entityManager.createNativeQuery(queryString.toString());

    List<Object[]> results = query.getResultList();
    System.out.println(results);
    for (Object[] result : results) {
        System.out.println(result);
    }

It prints right answer for "System.out.println(results);", But don't enter into for each loop. Here error is :-

java.lang.String cannot be cast to [Ljava.lang.Object;

Upvotes: 1

Views: 2661

Answers (3)

uniknow
uniknow

Reputation: 938

Can you verify that there are results within the returned list by changing System.out.println(results); into something like System.out.println(results ==null ? "empty", results.size());

To me it seems that it is entering the loop because of the reported exception java.lang.String cannot be cast to [Ljava.lang.Object; but as Erna indicated within his answer above, the returned list might be a list of Strings instead of an array of Objects.

Upvotes: 0

Eran
Eran

Reputation: 393781

Based on the exception you got, it looks like query.getResultList() returns a List<String>, not List<Object[]>. Change your code to

List<String> results = query.getResultList();
System.out.println(results);
for (String result : results) {
    System.out.println(result);
}

Upvotes: 4

You are printing the array wrong

Do instead:

for (Object[] result : results) {
        for (Object obj : result) {
        System.out.println(obj);
    }
}

OR EVEN BETTER

 for (Object[] result : results) {
           Arrays.toString(result));
    }

Upvotes: 1

Related Questions