|
In the prior examples, the keys and values of each store were represented using separate classes. For example, a PartKey and a PartValue class were used. Many times it is desirable to have a single class representing both the key and the value, for example, a Part class.
Such a combined key and value class is called an entity class and is used along with an entity binding. Entity bindings combine a key and a value into an entity when reading a record from a collection, and split an entity into a key and a value when writing a record to a collection. Entity bindings are used in place of value bindings, and entity objects are used with collections in place of value objects.
The example program illustrates:
Some reasons for using entities are:
Of course, instead of using an entity binding, you could simply create the entity yourself after reading the key and value from a collection, and split the entity into a key and value yourself before writing it to a collection. But this would detract from the convenience of the using the Java collections API. It is convenient to obtain a Part object directly from Map.get and to add a Part object using Set.add . Collections having entity bindings can be used naturally without combining and splitting objects each time a collection method is called; however, an entity binding class must be defined by the application.
In addition to showing how to use entity bindings, this example illustrates a key feature of all bindings: Bindings are independent of database storage parameters and formats. Compare this example to the prior Index example and you'll see that the Sample and SampleViews classes have been changed to use entity bindings, but the SampleDatabase class was not changed at all. In fact, the Entity program and the Index program can be used interchangeably to access the same physical database files. This demonstrates that bindings are only a "view" onto the physical stored data. Note that formats are managed by the SampleDatabase class because they define the physical syntax of the stored data.
The complete source of the final version of the example program is included in the Berkeley DB distribution.
Copyright (c) 1996-2003 Sleepycat Software, Inc. - All rights reserved.