I am using JPA for my project and I would like to know that there is any way to count its subclass for one to many relationship. For example, let's say there is an order class that has multiple items and I need to display a list of orders.
@Entity
@Table
public class Order {
...
@Id
private Long orderId;
@OneToMany
private List<OrderItem> orderItems;
}
For the list, I need to display how many items are ordered and how many items are canceled. So, I added functions such that
@OneToMany
private List<OrderItem> orderItems;
...
public Long countOrderedItems() {
Long count = 0;
orderItems.forEach(orderItem -> {
if(orderItem.getStatus().equals(Status.ORDERED)){
count++;
}
});
return count;
}
public Long countCancelItems() {
Long count = 0;
orderItems.forEach(orderItem -> {
if(orderItem.getStatus().equals(Status.CANCEL)){
count++;
}
});
return count;
}
However, this looks inefficient and I want to get these two values directly when I get data from repository like:
@Query("SELECT o, (SELECT COUNT(oi) FROM OrderItem oi WHERE oi.Order.orderId = o.orderId AND oi.status = 'ORDERED') FROM Order o");
But, I know this is not correct JPQL and I would like to know how to get these values efficiently in JPA.
Use JPA 2.1 feature JOIN ON