Interface for specialized encoding and decoding of Object
s of arbitrary type in a {@link Value}. Persistit contains built-in logic to encode objects of certain classes. For other classes, if there is no registered ValueCoder
, Persistit uses standard object serialization to generate a byte array that represents the state of that object in the database.
By implementing and registering a ValueCoder
with the current {@link CoderManager} you can override this default encoding. Typically thecustomized encoding of an object will be much shorter than that produced by serialization because the customized encoding classes by their Persistit class handles (see {@link com.persistit.ClassIndex}) rather than their names. In addition, standard serialization serializes the entire graph of other objects that may be directly or indirectly referred to by the object being made persistent. This behavior may result in storing much more data than is required, and more importantly, may result in incorrect semantics. A customized ValueEncoder
can handle persistence of fields that refer to other objects in a manner that is semantically appropriate for the specific object. Note that if a class has a ValueCoder
, it can be stored in Persistit even if it does not implement java.io.Serializable
.
A ValueCoder
implements methods to convert an object of some class to an array of bytes and back again. Typically the implementation of a ValueCoder
will simply invoke the Value
's put
methods to write the fields into the Value
. For example, the following code defines a class, and a ValueCoder
to store and retrieve it.
class MyClass { int id; int anotherInt; String someString; MyClass anotherMyClass; } class MyClassValueCoder implements ValueCoder { public void put(Value value, Object object, CoderContext context) { MyClass mc = (MyClass) object; value.put(mc.id); value.put(mc.anotherInt); value.put(mc.someString); value.put(mc.anotherMyClass == null ? -1 : mc.anotherMyClass.id); } public Object get(Value value, Class clazz, CoderContext context) { MyClass mc = new MyClass(); mc.id = value.getInt(); mc.anotherInt = value.getInt(); mc.someString = value.getString(); mc.anotherMyClass = lookupMyClass(value.getInt()); return mc; } }
The application should register this ValueCoder
before attempting to invoke {@link Value#put(Object)} on an object of classMyClass
or to retrieve an object value using {@link Value#get()}that will resolve to a MyClass
. Generally this means that applications should register all ValueCoder
s and KeyCoder
s during application startup, immediately after invoking {@link com.persistit.Persistit#initialize}. For example:
@version 1.0... try { Persistit.initialize(); CoderManager cm = Persistit.getInstance().getCoderManager(); cm.registerValueCoder(new MyClassValueCoder()); cm.registerValueCoder(new MyClassValueCoder2()); ... cm.registerKeyCoder(new MyClassKeyCoder()); ... } catch (PersistitException e) { ... }
|
|
|
|
|
|
|
|
|
|