I have two entities: category and product. They are associated and category is a parent:
@Entity
@Table(name = "categories")
public class Category {
@Id
@GeneratedValue(generator = "inc")
@GenericGenerator(name = "inc", strategy = "increment")
private int id;
private String name;
private int totalQuantity;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "category")
private Set<Product> products;
public Category(int id, String name, int totalQuantity, Set<Product> products) {
this.id = id;
this.name = name;
this.totalQuantity = totalQuantity;
this.products = products;
}
Product entity:
@Entity
@Table(name = "products")
public class Product {
@Id
@GeneratedValue(generator = "inc")
@GenericGenerator(name = "inc", strategy = "increment")
private int id;
private String name;
private int amount;
@ManyToOne
@JoinColumn(name = "category_id")
private Category category
}
(totalQuantity is the sum of the amount 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:
@Query("SELECT new com.example.demo.category.Category(p.category.id, p.category.name, SUM(p.amount), ) FROM Product p GROUP BY p.category.id")
List<Category> findAll();
EDIT:
To better show the goal, I add my category view ("Front", "Back-end") with products associated with each of them:
