title: JPQL How to sum up a given property of children and fetch these children avoiding n + 1 selections?
body: <p>I have two entities: category and product. They are associated and category is a parent:</p>
  <pre><code>@Entity
  @Table(name = &quot;categories&quot;)
  public class Category {
      @Id
      @GeneratedValue(generator = &quot;inc&quot;)
      @GenericGenerator(name = &quot;inc&quot;, strategy = &quot;increment&quot;)
      private int id;
      private String name;
      private int totalQuantity;
  
      @OneToMany(fetch = FetchType.LAZY, mappedBy = &quot;category&quot;)
      private Set&lt;Product&gt; products;
    
      public Category(int id, String name, int totalQuantity, Set&lt;Product&gt; products) {
          this.id = id;
          this.name = name;
          this.totalQuantity = totalQuantity;
          this.products = products;
      }
  </code></pre>
  <p>Product entity:</p>
  <pre><code>@Entity
  @Table(name = &quot;products&quot;)
  public class Product {
      @Id
      @GeneratedValue(generator = &quot;inc&quot;)
      @GenericGenerator(name = &quot;inc&quot;, strategy = &quot;increment&quot;)
      private int id;
      private String name;
      private int amount;
      @ManyToOne
      @JoinColumn(name = &quot;category_id&quot;)
      private Category category
  }
  </code></pre>
  <p>(<code>totalQuantity</code> is the sum of the <code>amount</code> of products associated to the category )
  I want to get all categories and all associated products in such a way as to prevent n + 1 and do a summation. This is my query that is wrong/uncompleted because I have no idea how I can do/complete it:</p>
  <pre><code>@Query(&quot;SELECT new com.example.demo.category.Category(p.category.id, p.category.name, SUM(p.amount), ) FROM Product p GROUP BY p.category.id&quot;)
  List&lt;Category&gt; findAll();
  </code></pre>
  <p>EDIT:
  To better show the goal, I add my category view (&quot;Front&quot;, &quot;Back-end&quot;) with products associated with each of them:
  <a href="https://i.stack.imgur.com/fU9qY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fU9qY.png" alt="Category view" /></a></p>