Mapping calculated properties with JPA

后端 未结 3 591
生来不讨喜
生来不讨喜 2021-01-04 11:35

Is there a way to map a calculated property using JPA?

Assuming I have an Invoice object with one or more InvoiceLineItems within it, I wan

3条回答
  •  醉梦人生
    2021-01-04 12:39

    Perhaps the PrePersist annotation can be used for this.

    @Column(name = "TOTAL_AMOUNT")
    private BigDecimal totalAmount;
    
    @PrePersist
    public void updateTotalAmount() {
        BigDecimal amount = BigDecimal.ZERO;
        for (InvoiceLineItem lineItem : lineItems) {
            amount = amount.add(lineItem.getTotalAmount());
        }
        this.totalAmount = amount;
    }
    

提交回复
热议问题