类型转换器

类型转换使Model内字段不一定是数据库类型的。它们把该字段的值转换成在数据库可以定义的类型。它们还定义了当一个模型被加载的方式,我们使用转换器重新创建字段。注意:TypeConverter只能转化成常规列,由于数据中的非确定性映射,PrimaryKey 或ForeignKey是不能转化的。

这些转换器在所有数据库共享。

如果我们指定model值作为Model 类的话,可能有一些字段非常意外的行为被定义为Column.FOREIGN_KEY

下面是实现LocationConverter,把位置转化成字符串:

2. // First type param is the type that goes into the database
3. // Second type param is the type that the model contains for that field.
4. @com.raizlabs.android.dbflow.annotation.TypeConverter
5. public class LocationConverter extends TypeConverter<String,Location> {

7. @Override
8. public String getDBValue(Location model) {
9. return model == null ? null : String.valueOf(model.getLatitude()) + "," + model.getLongitude();
10. }

12. @Override
13. public Location getModelValue(String data) {
14. String[] values = data.split(",");
15. if(values.length < 2) {
16. return null;
17. } else {
18. Location location = new Location("");
19. location.setLatitude(Double.parseDouble(values[0]));
20. location.setLongitude(Double.parseDouble(values[1]));
21. return location;
22. }
23. }
24. }

要使用LocationConverter,使用类型转换器,我们只需添加类作为我们的表中的字段:

2. @Table(...)
3. public class SomeTable extends BaseModel {

6. @Column
7. Location location;

9. }

列具体的类型转换器

作为3.0的TypeConverter可以在column-by-column基础上使用。

2. @Table(...)
3. public class SomeTable extends BaseModel {

6. @Column(typeConverter = SomeTypeConverter.class)
7. Location location;

9. }

注: enum 类举希望从默认枚举转换(从枚举到字符串),你必须定义一个自定义类型转换为列。