Custom Type Handler
Custom type handlers allow taking control over the storing and loading procedure of specific java types. This is useful to optimize the performance for storing complex objects or in the rare case that it is not possible to store a type with the default type handlers.
There are two strategies for a simplified type handler implementation.
Implementing a class that extends
CustomBinaryHandlerand defines a sequence of
BinaryFields via the
#Field~static pseudo-constructor methods. Everything else like setting the name, calculating the binary offsets, etc. is then done implicitly via reflection.
This example implements a custom type handler for the
java.awt.image.BufferedImageclass. Instead of storing the rather complex object structure of that class the image is serialized as PNG image format using
javax.imageio.ImageIOinto a byte array. This byte array is then stored by MicroStream.
The custom type handler must be registered in the
CustomTypeHandlerRegistryto enable it:
EmbeddedStorageManager storage = EmbeddedStorage
Implementing a class can be skipped altogether by using the method
Binary#TypeHandlerand passing the
BinaryFields directly. Registering such a generically created TypeHandler is not required, either, since Version 3 of MicroStream brought a solution to just define a static method in the entity class that will be recognized and used by MicroStream.
The following is a simple technical example on how a custom binary handler can be easily defined and technically leveraged to optimize storage behavior. E.g. imagine having millions of such objects that now only create 1 database record with a fraction of the required storage space instead of 4 records but hold the same information.
public class Employee
* Fields with primitive data are (for whatever reason, e.g. project
* design rules) all object types, but records should be stored as
* efficient as possible, i.e. without overhead of references and value objects.
* MicroStream's generic type analysis does not know of this and hence cannot
* do it. But defining a custom type handler can
String id ;
Double salary ;
// constructor, getters, setters, etc
* The entity class must just contain "any" method returning a suitable type
* handler and MicroStream will recognize it and use the returned handler
* Type type handler just needs to specify the entity class and define a list
* of fields comprised of (name, getter, setter) in arbitrary order.
static BinaryTypeHandler<Employee> provideTypeHandler()
e -> Long.parseLong(e.id),
(e, value) -> e.id = String.valueOf(value)
e -> e.dateOfBirth.getTime(),
(e, value) -> e.dateOfBirth = new Date(value)
e -> e.salary.longValue(),
(e, value) -> e.salary = Double.valueOf(value)