The application model layer consists of the EntityModel class and its associates; the EntityTableModel, which provides a table representation of entities and the EntityEditModel which provides the CRUD operations.
An EntityModel always contains an EntityEditModel instance and usually contains a EntityTableModel as well. A default edit model implementation is created automatically by the EntityTableModel if one is not supplied via a constructor argument.
public class AddressModel extends SwingEntityModel {
public AddressModel(EntityConnectionProvider connectionProvider) {
super(Address.TYPE, connectionProvider);
}
}
public class CustomerAddressModel extends SwingEntityModel {
public CustomerAddressModel(EntityConnectionProvider connectionProvider) {
super(new CustomerAddressTableModel(connectionProvider));
}
}
1. Detail models
An EntityModel can contain one or more detail models, usually based on foreign key relationships.
public class StoreApplicationModel extends SwingEntityApplicationModel {
public StoreApplicationModel(EntityConnectionProvider connectionProvider) {
super(connectionProvider, List.of(createCustomerModel(connectionProvider)));
}
private static SwingEntityModel createCustomerModel(EntityConnectionProvider connectionProvider) {
CustomerModel customerModel =
new CustomerModel(connectionProvider);
CustomerAddressModel customerAddressModel =
new CustomerAddressModel(connectionProvider);
customerModel.detailModels().add(customerAddressModel);
//populate the model with rows from the database
customerModel.tableModel().items().refresh();
return customerModel;
}
}
2. Event binding
The model layer classes expose a number of Event, State and Value observers.
The example below prints, to the standard output, all changes made to a given attribute value as well as a message indicating that a table refresh has started.
public class CustomerModel extends SwingEntityModel {
public CustomerModel(EntityConnectionProvider connectionProvider) {
super(new CustomerTableModel(connectionProvider));
bindEvents();
}
private void bindEvents() {
CustomerTableModel tableModel = (CustomerTableModel) tableModel();
tableModel.selection().items()
.addConsumer(selected ->
System.out.println("Items selected: " + selected));
tableModel.items().refresher().result()
.addListener(() -> System.out.println("Refresh successful"));
CustomerEditModel editModel = (CustomerEditModel) editModel();
editModel.afterInsert()
.addConsumer(inserted ->
System.out.println("Entities inserted" + inserted));
editModel.editor().value(Customer.FIRST_NAME).edited()
.addConsumer(firstName ->
System.out.println("First name changed to " + firstName));
}
}