Composition is done with Java interfaces and Annotations. Example;
public void addLineItem( LineItem item )
{
String productCode = item.getProductCode();
int quantity = item.getQuantity();
inventory.remove( productCode, quantity );
next.addLineItem( item );
}
public void removeLineItem( LineItem item )
{
String productCode = item.getProductCode();
int quantity = item.getQuantity();
inventory.add( productCode, quantity );
next.removeLineItem( item );
}
}
But Qi4j also support persistence directly in its Core. Simply by changing the interface it extends to EntityComposite;
Now, let's say that we want to send a mail to sales@mycompany.com when the order is confirmed. This is a SideEffect, and will execute after the Constraints, Concerns and Mixins. We add the SideEffect to the OrderComposite;
public void confirmOrder()
{
List<LineItem> items = hasItems.getLineItems();
StringBuilder builder = new StringBuilder();
builder.append( "An Order has been made.\n\n\n" );
builder.append( "Total amount:" );
builder.append( order.getOrderAmount() );
builder.append( "\n\nItems ordered:\n" );
for( LineItem item : items )
{
builder.append( item.getName() );
builder.append( " : " );
builder.append( item.getQuantity() );
builder.append( "\n" );
}
mailer.send( "sales@mycompany.com", builder.toString() );
}
}
@ThisCompositeAs is telling Qi4j that the SideEffect needs a reference to the Composite instance that it belongs to. By asking for both the Order and the HasLineItems types, we get type-safety and don't need to bother with casts. In fact, Qi4j will ensure that you can't even cast the order to the HasLineItems type. By not referencing the aggregated interface OrderComposite, we reduce the coupling of this SideEffect and it can be used in any other Composite where the Order and HasLineItems combination is used.
So, build the report, send it via the MailService.
In this short introduction, we have covered the essence of Qi4j. We have looked at what is a Composite, seen some of the Fragments in action, and how simple it is to turn a Composite into a persisted Composite, known as an EntityComposite.