> For the complete documentation index, see [llms.txt](https://manual.docs.microstream.one/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://manual.docs.microstream.one/4.0/data-store/customizing/custom-type-handler.md).

# Custom Type Handler

{% hint style="warning" %}
**This is the manual for older MicroStream versions (Version < 5.0).**

**The new documentation (Version >= 5.0) is located at:**

[https://docs.microstream.one/](https://docs.microstream.one/manual)
{% endhint %}

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.

## Implementation

There are two strategies for a simplified type handler implementation.

### A Custom Binary Handler

Implementing a class that extends `CustomBinaryHandler` and defines a sequence of `BinaryField`s via the `#Field~` static pseudo-constructor methods. Everything else like setting the name, calculating the binary offsets, etc. is then done implicitly via reflection.

{% hint style="info" %}
[Example on GitHub](https://github.com/microstream-one/examples/blob/master/customTypeHandler/src/main/java/one/microstream/sampler/customtypehandler/CustomBufferedImageHandler.java)

This example implements a custom type handler for the `java.awt.image.BufferedImage` class. Instead of storing the rather complex object structure of that class the image is serialized as PNG image format using `javax.imageio.ImageIO` into a byte array. This byte array is then stored by MicroStream.
{% endhint %}

The custom type handler must be registered in the `CustomTypeHandlerRegistry` to enable it:

```java
EmbeddedStorageManager storage = EmbeddedStorage
     .Foundation(WORKINGDIR)
     .onConnectionFoundation(f ->
          f.registerCustomTypeHandlers(new CustomBufferedImageHandler())
     )
     .start(ROOT);
```

### A Static Provider Method

Implementing a class can be skipped altogether by using the method `Binary#TypeHandler` and passing the `BinaryField`s 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.

```java
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     ;
	Date   dateOfBirth;
	
	// 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 
	 * automatically.
	 * 
	 * 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()
	{
		return Binary.TypeHandler(
		  Employee.class,
			Binary.Field_long("id",
				e -> Long.parseLong(e.id),
				(e, value) -> e.id = String.valueOf(value)
			),
			Binary.Field_long("dateOfBirth",
				e -> e.dateOfBirth.getTime(),
				(e, value) -> e.dateOfBirth = new Date(value)
			),
			Binary.Field_double("salary",
				e -> e.salary.longValue(),
				(e, value) -> e.salary = Double.valueOf(value)
			)
		);
	}
	
}
```

{% hint style="info" %}
Full example is available on [GitHub](https://github.com/microstream-one/examples/blob/master/customTypeHandler/src/main/java/one/microstream/sampler/customtypehandler/Employee.java).
{% endhint %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://manual.docs.microstream.one/4.0/data-store/customizing/custom-type-handler.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
