Pregunta

I'm learning JPA and was wondering how can we generate reports using the query below.

Query query = em
            .createQuery("SELECT t.firstName, t.lastName, t.salary FROM Teacher t");

    List results = query.getResultList();
    Object[] objects = results.toArray(new Object[results.size()]);
    for (Object object : objects) {
        System.out.println(object);// here I want to print firstName, lastName
    }

I understand that the getResultList() method returns list of array of objects. But I want to print the firstName, lastName and salary here. How can I do that? I cannot simply cast Object into String.

¿Fue útil?

Solución

Try this out.

List<Object[]> list = query.getResultList();
for (int index = 0; index < list.size(); index++) {
    Object[] objArr = list.get(index); //this will return a row of your result into objArr
    for (int j = 0; j < 3; j++) {
        //here, you are now iterating through the columns in each row. Since your select query has 3 columns j <3 in the for loop
        System.out.println(objArr[j].toString());
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top