Skip Headers

# Using Batch Reading

Previous

Next

Batch reading propagates query selection criteria through an object's relationship attribute mappings. You can also nest batch read operations down through complex object graphs. This significantly reduces the number of required SQL select statements and improves database access efficiency.

Consider the following guidelines when you implement batch reading:

- Use batch reading for processes that read in objects and all their related objects.

- Do not enable batch reading for both sides of a bidirectional relationship.

- Avoid nested batch read operations, because they result in multiple joins on the database, slowing query execution.

For more information, see "Reading Case 2: Batch Reading Objects".

For example, in reading n employees and their related projects, TopLink may require n + 1 select operations. All employees are read at once, but the projects of each are read individually. With batch reading, all related projects can also be read with one select operation by using the original selection criteria, for a total of only two select operations.

To implement batch reading, use one of the following methods:

- To add the batch read attribute to a query, use the `query.addBatchReadAttribute(Expression anExpression)` API.

  For example:

      …
      ReadAllQuery raq = new ReadAllQuery(Trade.class);
      ExpressionBuilder tradeBuilder = raq.getBuilder();
      …
      Expression batchReadProduct = tradeBuilder.get("product");
      readAllQuery.addBatchReadAttribute(batchReadProduct);
      Expression batchReadPricingDetails = batchReadProduct.get("pricingDetails");
      readAllQuery.addBatchReadAttribute(batchReadPricingDetails);
      …

- Add batch reading at the mapping level for a descriptor. Use either TopLink Workbench or a descriptor amendment method to add the `setUsesBatchReading` API on the descriptor's relationship mappings.

  For example:

      public static void amendTradeDescriptor(Descriptor theDescriptor) {
          OneToOneMapping productOneToOneMapping =        theDescriptor.getMappingForAttributeName("product");
          productOneToOneMapping.setUsesBatchReading(true);
      }

You can combine batch reading and indirection to provide controlled reading of object attributes. For example, if you have one-to-one back pointer relationship attributes, you can defer back pointer instantiation until the end of the query, when all parent and owning objects are instantiated. This prevents unnecessary database access and optimizes TopLink cache use.