Issue
I'm trying to return an array of Double from my repository class. But the repository returns only the first element (i.e. avg(colA)) in the array and modifies the array size to 1.
Repository class:
.
.
.
@Query(value="select avg(colA), avg(colB), avg(colC) from Table where ID=?1 group by ID", nativeQuery=true)
public Double[] findData(long id);
.
.
.
My service class:
.
.
.
@Autowired
TableRepository repo;
long Id = 123;
Double[] arr = new Double[3];
arr = repo.findData(Id);
system.Out.println(arr.length); //Returns 1, which is supposed to be 5
system.Out.println(arr[1]); // ArrayIndexOutOfBoundsException
.
.
.
What I'm trying: Return an array with elements having average values of the columns. Ideally the elements should have, arr[0] = avg(colA), arr[1] = avg(colB), arr[2] = avg(colC). But the returned array has only arr[0] in it and the sizeof(arr) is just 1 instead of 3. I'm not able to figure out why only the first value is being returned? The query works fine on the database. Is it related to some array referencing? How to overcome this without writing a separate class to act as the return type?
Solution
Return List<Double[]>
instead of Double[]
.
I populated an H2 table:
INSERT INTO billionaires (first_name, last_name, career, num1, num2) VALUES
('Aliko', 'Dangote', 'Billionaire Industrialist', 500, 222),
('Bill', 'Gates', 'Billionaire Tech Entrepreneur', 599, 333),
('Folrunsho', 'Alakija', 'Billionaire Oil Magnate', 600, 444);
then tested Thomas' theory by creating two methods:
@Query(value="select avg(id), avg(num1), avg(num2) from billionaires", nativeQuery=true)
Double[] findData();
@Query(value="select avg(id), avg(num1), avg(num2) from billionaires", nativeQuery=true)
List<Double[]> findData2();
And called both:
System.out.println("With Double[]:");
Double[] avgs = repo.findData();
System.out.println(Arrays.toString(avgs));
System.out.println("With List<Double[]>:");
List<Double[]> avgs2 = repo.findData2();
avgs2.forEach(doubles -> System.out.println(Arrays.toString(doubles)));
Output:
With Double[]:
[2.0]
With List<Double[]>:
[2.0, 566.0, 333.0]
Answered By - Most Noble Rabbit