Interface DerivedValue<T>
- Type Parameters:
T- the value type
- All Superinterfaces:
Serializable
- Functional Interface:
- This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.
Derived attributes compute their values from other attributes within the same entity or from related entities. They provide calculated fields, formatting, concatenation, and other derived values without being stored in the database.
Derived attributes are defined using value providers that receive source values and compute the derived result:
// Computes the invoice line total from the quantity and unit price
class InvoiceLineTotal implements DerivedValue<BigDecimal> {
@Override
public BigDecimal from(SourceValues values) {
Integer quantity = values.get(InvoiceLine.QUANTITY);
BigDecimal unitPrice = values.get(InvoiceLine.UNITPRICE);
if (unitPrice == null || quantity == null) {
return null;
}
return unitPrice.multiply(BigDecimal.valueOf(quantity));
}
}
// In the entity definition
InvoiceLine.TOTAL.as()
.derived()
.from(InvoiceLine.QUANTITY, InvoiceLine.UNITPRICE)
.with(new InvoiceLineTotal())
.caption("Total");
// Usage
Entity invoiceLine = entities.entity(InvoiceLine.TYPE)
.with(InvoiceLine.UNITPRICE, BigDecimal.valueOf(0.99))
.with(InvoiceLine.QUANTITY, 2)
.build();
// Derived values are computed automatically
BigDecimal total = invoiceLine.get(InvoiceLine.TOTAL); // 1.98
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeInterfaceDescriptionstatic interfaceProvides the source values from which to derive a value. -
Method Summary
Modifier and TypeMethodDescriptionfrom(DerivedValue.SourceValues values) Called only when the entity has every source value, null or not, the derived value being null where one is missing, for example a column not selected.static DerivedValue.SourceValuessourceValues(Attribute<?> derivedAttribute, Map<Attribute<?>, Object> values)
-
Method Details
-
from
Called only when the entity has every source value, null or not, the derived value being null where one is missing, for example a column not selected. A missing value is not a null one, which would derive a value the source values do not support.
Must be total over the source values, that is, return a value or null for every combination of them, including all null. A cached derived value is computed for every attribute of an entity being made immutable, not only for the ones a caller happens to read, so a provider throwing on some combination throws from
Entity.immutable()rather than from the read it would once have failed.- Parameters:
values- the source values, mapped to their respective attributes, each one present- Returns:
- the derived value
-
sourceValues
static DerivedValue.SourceValues sourceValues(Attribute<?> derivedAttribute, Map<Attribute<?>, Object> values) - Parameters:
derivedAttribute- the derived attributevalues- the values- Returns:
- a new
DerivedValue.SourceValuesinstance
-