简体   繁体   中英

spring data JPA: How to execute aggregate functions

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM