The built-in inheritance capability of SQL repositories lets you easily query across a complex hierarchy of sub-types, and helps optimize performance. For example, given the previous model, the following query can return both shirt and shorts items:
get all clothing items with a shipping weight > 2 pounds
The code for this query looks like this:
// get hold of the repository Repository gsa = ...; // get the view to use for querying "clothing" type items RepositoryView clothingView = gsa.getView("clothing"); // get a query builder QueryBuilder qb = clothingView.getQueryBuilder(); // build the query QueryExpression weightLimit = qb.createConstantQueryExpression(new Integer(2)); QueryExpression itemWeight = qb.createPropertyQueryExpression("shippingWeight"); Query q = qb.createComparisonQuery(itemWeight, weightLimit, QueryBuilder.GREATER_THAN); // run the query RepositoryItem[] items = clothingView.executeQuery(q); // separate the shirts and shorts and do whatever with them for (int i=0; i<items.length; i++) { RepositoryItem item = items[i]; // all clothing items have a name and a description logDebug("clothing: " + item.getPropertyValue("name") + ' ' + item.getPropertyValue("description")); // the ItemDescriptor defines the "type" of an item RepositoryItemDescriptor desc = item.getItemDescriptor(); // now we do different things, depending on the // type of clothing item we have if (desc.getItemDescriptorName().equals("shirt") { // shirts have a property called "season" logDebug("\tshirt, season = " + item.getPropertyValue("season")); // do shirt-related things myShirtProcessor(item); } else { // shorts have a property called "pleated" logDebug("\tshirt, season = " + item.getPropertyValue("pleated")); // do shorts-related things myShortsProcessor(item); } }
This example uses the name of the item descriptor to determine the item type. You can also look at the value of the type
property declared in your template. In the example, the enumerated properties are defined with the useCodeForValue
attribute set to true
. As result, the query looks like this:
... RepositoryItem item = items[i]; Integer itemTypeCode = (Integer)item.getPropertyValue("type"); if (itemTypeCode.intValue() == 0) { ... shirts ... } else { ... shorts ... }
Choice of one approach over another is largely a matter of style. The item descriptor approach uses the actual name like shirt
or shorts
. The type attribute approach uses the type code stored in the clothing table: typically something like 0
or 1
, as in this case.