Home > Back-end >  thymeleaf - sum of objects in list inside a list
thymeleaf - sum of objects in list inside a list

Time:03-17

I use spring boot thymeleaf and mySQL DB I have 3 entities:

  • Category
  • SubCategory
  • Porducts

The current table

I would like to show the sum of products in the table

This is the code to show the sum of sub category:

  <tbody>
    <tr th:each="category : ${categories}">
      <td th:text="${category.name}" />
      <td th:text="${#lists.size(category.subCategories)}" />
    </tr>
  </tbody>

CodePudding user response:

You can use collection projection and aggregate functions to accomplish this:

<tbody>
  <tr th:each="category : ${categories}">
    <td th:text="${category.name}" />
    <td th:text="${#lists.size(category.subCategories)}" />
    <td th:text="${#aggregates.sum(category.subCategories.![#lists.size(products)])}" />
  </tr>
</tbody>

The expressions category.subCategories.![#lists.size(products)] produces a list of the products in subCategories, which you can just sum using #aggregates.sum.

  • Related