Calculated Field JPA Spring Boot

Asked

Viewed 500 times

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 various Sales Items (products). Partial total per Item of Sale (product price * quantity) is calculated correctly.

But when I go to valvular the total of the Sale the total of the Sale 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;
}

1 answer

1

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 zero value 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;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.