Custom types
Sometimes, you need to store a type that can't be handled out of the box. ObjectBox let's you define a custom converter (a pair of functions) that takes care of encoding & decoding properties.
The following built-in types, their aliases and named types based on them are recognized as ObjectBox and stored as an appropriate internal type:
Defining a converter
To add support for a custom type, you can map properties to one of the built-in types using a converter
annotation.
For example, you could define a color in your entity using a custom Color
struct and map it to an int32
. Or you can map the time.Time
to an int64
, though losing some precision - less than a millisecond, i. e. a thousandth of a second):
In the entity definition above, we instruct ObjectBox to store the DateCreated
field as a int64
while converting it to/from time.Time
when using in the program. ObjectBox will generate a binding code that will call the following two functions (both start with the prefix timeInt64
specified above):
Just to complete the example, those functions could be implemented like this:
Actually this converter for time.Time
is already part of the objectbox
package and used automatically when you mark a time.Time
property with `objectbox:"date"`.
Queries on custom types
When you use a converter, the actual value stored in the database is the result of the ...ToDatabaseValue()
call, e.g. int64
in the previous example. Therefore, when you want to compare the stored data in a query condition, make sure you use the converted value as well:
Things to look out for
You must not interact with the database (such as using Box
or ObjectBox
) inside the converter. The converter methods are called within a transaction, so for example getting or putting entities to a box will fail.
Your converter implementation must be thread safe as it can be called from multiple go routines in parallel. Try to avoid using global variables.
Query
is unaware of custom types. You have to use the primitive DB type for queries.
Last updated