3.14.3.3. Implement DistributionPolicy interface
Slice needs to determine which slice will persist a new instance.
The application can only decide this policy (for example, all PurchaseOrders before April 30 goes to slice One, all the rest goes to slice Two). This is why the application has to implement org.apache.openjpa.slice.DistributionPolicy and specify the implementation class in configuration
<property name="openjpa.slice.DistributionPolicy" value="com.acme.foo.MyOptimialDistributionPolicy"/>
The interface org.apache.openjpa.slice.DistributionPolicy is simple with a single method.
The complete listing of the documented interface follows:
public interface DistributionPolicy {
/**
* Gets the name of the slice where a given instance will be stored.
*
* @param pc The newly persistent or to-be-merged object.
* @param slices name of the configured slices.
* @param context persistence context managing the given instance.
*
* @return identifier of the slice. This name must match one of the
* configured slice names.
* @see DistributedConfiguration#getSliceNames()
*/
String distribute(Object pc, List<String> slices, Object context);
}
While implementing a distribution policy the most important thing to remember is collocation constraint.
Because Slice can not establish or query any cross-database relationship, all the related instances must be stored in the same database slice.
Slice can determine the closure of a root object by traversal of cascaded relationships.
Hence user-defined policy has to only decide the database for the root instance that is the explicit argument to EntityManager.persist() call.
Slice will ensure that all other related instances that get persisted by cascade are assigned to the same database slice as that of the root instance.
However, the user-defined distribution policy must return the same slice identifier for the instances that are logically related but not cascaded for persist.