Field Calculated JPA Spring Boot

2

I'd like help finding a calculated field. The problem is that it involves relationships.

I need to calculate the total of a Sale with multiple Selling Items (products). The partial total per Sales Item (product price * quantity) is calculated correctly.

But when I am going to value the total of the Sale, the total of the Sales Item comes null, in these codes:

// Item de Venda
@Transient
private Double total;

// Este código funciona ao consultar os itens de venda (separadamente)
public Double getTotal() {
    return this.product.getPrice() * this.quantity;
}
// Venda
@Transient
private Double total;

public Double getTotal() {
    if (!sellItems.isEmpty()) {
        for (SellItem item : sellItems){
            // Essa linha dá NullPointer pois o valor é null.
            this.total += item.getTotal();
        }
    }

    return this.total;
}
    
asked by anonymous 10.07.2016 / 00:01

1 answer

0

The default value of a Double variable in Java is null, so when you declare a variable without initializing it, its initial value will be null. Initialize the total variable with the value zero first as follows:

public Double getTotal() {
    this.total= new Double(0.0);

    if (!sellItems.isEmpty()) {
        for (SellItem item : sellItems){
            // Essa linha dá NullPointer pois o valor é null.
            this.total += item.getTotal();
        }
    }

    return this.total;
}
    
25.07.2016 / 13:25