Reading Models Programmatically

Platform provides three main avenues for reading models: the model read API, views, and reports. The model read API is used primarily in programmatic access while the latter two are used to display information to users. Views are covered in the next section. Reports are covered in the chapter titled Reporting in this user guide.

Model Read API

The primary entry point for the model read API is the ModelDataService interface. You've seen the ModelDataService in previous examples when reading models.

You can read a model or a collection of models using the ModelDataService in several ways:


  • Surrogate IDs— Use the readById or readByIds to retrieve models by their surrogate IDs

  • Views— Use the readByView method to retrieve models using an existing view

  • SQL Fragments— Use the read method to retrieve models filtered by arbitrary filter fragments

Reading using the surrogate ID is the simplest method of retrieving a model from the database:

PlatformUserContext userContext = (...) //omitted - get the user context
ModelDataService modelDataService = Services.get(ModelDataService.class);
Book book = modelDataService.readById(Book.class, 10000L, userContext);
Map<Long,Book> books = modelDataService.readByIds(Book.class, Arrays.asList(10000L, 10001L), userContext);

You can also reuse views defined for a model and filter the view as necessary:

PlatformUserContext userContext = (...) //omitted - get the user context
ViewRequest<Book> bookView = new ViewRequest<Book>(Book.class, "BooksByTitle");
//query filters available for the view
List<Field> filters = modelDataService.getViewFilterFields(bookView, userContext);
boole an hasTitleFilter = false;
for(Field filter : filters) {
hasTitleFilter |= "Title".equals(filter.getId().getName());
}
if(!hasTitleFilter) {
throw new RuntimeException("Can't filter by title");
}
bookView.addFilter(Book.class, "Title", Arrays.asList("1984", "Fahrenheit 451"));
modelDataService.readByView(bookView, userContext);

If your existing views are not flexible enough, or you wish to dynamically determine filter criteria, you can use SQL fragments to retrieve the model:

PlatformUserContext userContext = (...) //omitted - get the user context
SqlParams params = new SqlParams();
params.setStringValue("Filter1", "Ray Bradbury");
params.setIntValue("Filter2", 300000);
List<Book> books = modelDataService.read(
Book.class,
userContext,
params,
ModelQuery.sqlFilter("author = $Filter1$"),
ModelQuery.sqlFilter("quantity_sold > $Filter2$"));

A drawback to the read method is that macros are not supported.