// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package javadb;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;

@Entity
@Table(name="myorder")
public class Order {
    private int orderId;
    private String customer;
    private List<OrderLine> orderLines;
    public Order() {
        this(0, "", new ArrayList<OrderLine>());
    }
    public Order(int orderId, String customer, List<OrderLine> orderLines) {
        this.orderId = orderId;
        this.customer = customer;
        this.orderLines = orderLines;
    }
    @Id
    @Column(name="orderid")
    public int getOrderId() {
        return orderId;
    }
    public void setOrderId(int orderId) {
        this.orderId = orderId;
    }
    @Column(name="customer")
    public String getCustomer() {
        return customer;
    }
    public void setCustomer(String customer) {
        this.customer = customer;
    }
    @OneToMany(mappedBy = "orderId",      // property name in child class - not field name in child table
               fetch = FetchType.EAGER)   // use FetchType.LAZY for lazy loading
    public List<OrderLine> getOrderLines() {
        return orderLines;
    }
    public void setOrderLines(List<OrderLine> orderLines) {
        this.orderLines = orderLines;
    }
    @Transient
    public BigDecimal getCost() {
        BigDecimal res = BigDecimal.ZERO;
        for(OrderLine ol : orderLines) {
            res = res.add(ol.getItemCost());
        }
        return res;
    }
}
