Reputation: 1822
I am using Spring Data JPA and I have a requirement where I need to execute the SQL query as below:
select key_1, sum(key_2), sum(key_3) from table_1
where key_1 in ('1', '2') and {dynamic_columns} group by key_1;
For dynamic columns, I am using Spring Data JPA Specifications but I am not sure how can I write the aggregate functions like sum() on multiple columns.
Upvotes: 0
Views: 5025
Reputation: 41
With Spring Data JPA you have a few options in a spring repository.
References: Baeldung - Spring data JPA Spring.io - Spring data JPA
Specify a native query
@Query(value="select key_1, sum(key_2) ...", nativeQuery=true)
Optional<Object[]> getAggregates;
Use the providers (HQL for hibernate etc. query language)
@Query(value="select e.key_1, sum(e.key_2) from entity e ...")
Optional<Object[]> getAggregates;
You'll use objects here because you are not returning a specific entity you are adding custom (aggregate) columns. If you were returning a specific entity with a JPA repository you could return that entity instead of Object[]. Each item inside the object array will correspond to a columnof data, if you had multiple rows here you would use:
Optional<List<Object[]>> getAggregates;
Finally, if you have not used optionals before you will get your object array by:
if(objectsOptional.isPresent()) {
Objects[] objects = objectsOptional.get();
...
}
If this isn't what you were looking for i'll need more information to help you out.
Upvotes: 2