how to iterate through JPA response and get values from it

Viewed 843

code in the repository is

@Query("select divisionName, count(stundeName)FROM StudentDetails GROUP BY divisionName")
    public List<Object> getDivisionCount();

and code in service is

List <Object> countList= studentDetailsRepository.getDivisionCount();

now I want to iterate through countList and categories then into different categories, I tried this

for(int i=0;i< countList.size();i++ )
    System.out.println(countList.get(i).getClass().getDeclaredField('count'));

it's not working and giving an error

3 Answers

It is better to use a projection over the JPA response. The one option is to use the interface-baased projection. In your case the query might look like this:

@Query(value = "SELECT s.divisionName AS divisionName, count(s.stundeName) AS stundeName FROM StudentDetails AS s GROUP BY s.divisionName")
public List<StudentDetails> getDivisionCount();

Then you need to create an interface like this:

public interface StudentDetails{
    String getDivisionName();
    String getStundeName();
}

You can iterate through your list of object like this and create an object array for each one in your list and then display it :

      for (Object object : countList){

        Object[] objArray = (Object[]) object;
        System.out.println((String)objArray[0]); // divisionName
        System.out.println((Integer)objArray[1]); // the count

      }
         

use JPAStreamer instant of raw query in production grade implementation. read more details in official doc, jpa_streamer. Or, Criteria Query

Related