orestoo
orestoo

Reputation: 15

Java Hibernate write query to sum values from list

From one query findAllByName(personName) I am getting back List Objects. I want to sum their age. So I make something like this:

  int sum =
                listPerson
                        .stream()
                        .mapToInt(PersonEntity::getAge)
                        .sum();

I know that I can use for example EntityManager and Query:

   Query query = em.createQuery(
              "SELECT SUM(p.age) FROM PErson p");

But it will sum age from all entities.

How can I write a query instead of this, to sum Person age from list, based on argument?

Upvotes: 0

Views: 919

Answers (1)

user1234SI.
user1234SI.

Reputation: 1860

You can write a function inside your repository which will return a Long or int (depends on your database size) type and is annotated with @Query

@Query(value = "SELECT SUM(age) FROM Person", nativeQuery = true)
Long getAgeSum();

EDIT: After your edit, the current method could be modified like this for

1) List arguments

@Query(value = "SELECT SUM(p.age) FROM Person p WHERE p.id IN :idList", nativeQuery = true)
Long getAgeSum(@Param("idList") List<String> idList);

2) Simple arguments

@Query(value = "SELECT SUM(p.age) FROM Person p WHERE p.jobName=:jobNameParam", nativeQuery = true)
Long getAgeSum(@Param("jobNameParam") String jobNameParam);

Upvotes: 1

Related Questions