0

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for taking time to help. The above options are not valid in my case as the where clause is condition based. For generating the where clause, I am using Spring-Data-JPA Specification but seem's that doesn't support aggregate functions.
the Object[] hint (or Any[] in kotlin) was the tip I needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.