TypeConverters
When building out Model
classes, you may wish to provide a different type of @Column
that from the standard supported column types. To recap the standard column types include:
String
,char
,Character
All numbers types (primitive + boxed)
byte[]
/Byte
Blob
(DBFlow's version)Date
/java.sql.Date
Booleans
Model
as@ForeignKey
or@ColumnMap
Calendar
BigDecimal
UUID
TypeConverter
do not support:
Any Parameterized fields.
List<T>
,Map<T>
, etc. Best way to fix this is to create a separate table relationshipConversion from one type-converter to another (i.e
JSONObject
toDate
). The first parameter ofTypeConverter
is the value of the type as if it was a primitive/boxed type.Conversion from custom type to
Model
, orModel
to a supported type.The custom class must map to a non-complex field such as
String
, numbers,char
/Character
orBlob
Define a TypeConverter
Defining a TypeConverter
is quick and easy.
This example creates a TypeConverter
for a field that is JSONObject
and converts it to a String
representation:
Once this is defined, by using the annotation @TypeConverter
, it is registered automatically across all databases.
There are cases where you wish to provide multiple TypeConverter
for same kind of field (i.e. Date
with different date formats stored in a DB). You can override a field's TypeConverter
locally at the @Column
level.
TypeConverter for specific @Column
@Column
In DBFlow, specifying a TypeConverter
for a @Column
is as easy as @Column(typeConverter = JSONConverter::class)
. What it will do is create the converter once for use only when that column is used.
Last updated