gpt4 book ai didi

java - JPA 计算其子类的一对多关系

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:51:45 25 4
gpt4 key购买 nike

我正在为我的项目使用 JPA,我想知道有什么方法可以计算其子类的一对多关系。例如,假设有一个包含多个项目的订单类,我需要显示一个订单列表。

@Entity
@Table
public class Order {
...
@Id
private Long orderId;
@OneToMany
private List<OrderItem> orderItems;
}

对于列表,我需要显示订购了多少商品以及取消了多少商品。所以,我添加了这样的功能

    @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;
}

但是,这看起来效率很低,我想在从存储库获取数据时直接获取这两个值,例如:

@Query("SELECT o, (SELECT COUNT(oi) FROM OrderItem oi WHERE oi.Order.orderId = o.orderId AND oi.status = 'ORDERED') FROM Order o"); 

但是,我知道这不是正确的 JPQL,我想知道如何在 JPA 中有效地获取这些值。

最佳答案

使用 JPA 2.1 功能 JOIN ON

select o, count(io), count(io2) from Order o 
left join o.irderItem oi on oi.status = 'ORDERED'
left join o.irderItem ui on ui.status = 'CANCELED'
group by s

The join condition used for a join comes from the mapping's join columns. This means that the JPQL user is normally free from having to know how every relationship is joined. In some cases it is desirable to append additional conditions to the join condition, normally in the case of outer joins. This can be done through the ON clause.

关于java - JPA 计算其子类的一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41109769/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com