带连接的Hibernate公式

时间:2017-05-19 08:01:20

标签: spring hibernate spring-boot

我有一个实体订单和一个实体order_items(1-> n关系)。 我想要一个字段,以显示相关订单项的总和(数量)的表。这些是我的实体:

    @Entity(name="ORDERS")
public class Order {

    @Id
    @GeneratedValue
    @Column (name="order_id")
    private long id;

    @OneToOne
    @JoinColumn(name="customer_id")
    private Customer customer;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "order", cascade =CascadeType.ALL)
    @JsonManagedReference
    private List<OrderItem> orderItems=new ArrayList();



@Entity(name="ORDER_ITEMS")
public class OrderItem {
    @Id
    @GeneratedValue
    @Column (name="order_item_id")
    private long id;

    @Column (name="quantity")   
    private int quantity;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "order_id", nullable = false)
    @JsonBackReference
    private Order order;

我想在Order实体中显示一个新字段,显示总数量(子项数量的总和)。 我已尝试按顺序添加字段但不起作用

@Formula("select sum(oi.quantity) from ORDER_ITEMS oi where oi.order_id= order_id)")
private int totalQuantity;

你能帮我解决一下吗?

1 个答案:

答案 0 :(得分:3)

解决方案

    @Formula("(select sum(oi.quantity) from ORDER_ITEMS  oi where oi.order_id= order_id)")
private int totalQuantity;