当存储对象类中使用了除String、Int 、Long等类型以外的复杂类型时候,objectBox的处理方法:
实现一个objectBox的PropertyConverter接口的类,将复杂类型处转换为基础类型
实体类
import android.net.Uri
import com.zbb.mine.em.SourceFrom
import com.zbb.mine.em.SourceFromConverter
import io.objectbox.annotation.Convert
import io.objectbox.annotation.Entity
import io.objectbox.annotation.Id
import io.objectbox.relation.ToMany
@Entity
class MusicEntity() {
// @assignable 手动管理id
@Id
var id: Long = 0
var name: String = ""
var singer: String = "未知"
var avatarUrl: String? = null
var avatarPath: String? = null
var url: String? = null
var path: String? = null
@Convert(converter = UriConverter::class, dbType = String::class)
var uri: Uri? = null
var lrcUrl: String? = null
var lrcPath: String? = null
var duration: Int = 0
var fileSize: Long = 0
var album: String? = null
@Convert(converter = SourceFromConverter::class, dbType = Int::class)
var from: SourceFrom = SourceFrom.UNKMOWN
// @Transient 不存放到数据库
// var xx
lateinit var groups: ToMany<GroupEntity>
override fun toString(): String {
return "MusicEntity(id=$id, name='$name', singer='$singer', avatarUrl=$avatarUrl, avatarPath=$avatarPath, url=$url, path=$path, uri=$uri, lrcUrl=$lrcUrl, lrcPath=$lrcPath, duration=$duration, fileSize=$fileSize, album=$album, from=$from)"
}
}
转换处理类
import android.net.Uri
import io.objectbox.converter.PropertyConverter
class UriConverter : PropertyConverter<Uri, String> {
override fun convertToDatabaseValue(entityProperty: Uri?): String {
return entityProperty?.toString() ?: ""
}
override fun convertToEntityProperty(databaseValue: String?): Uri? {
if (databaseValue == null) {
return null
} else {
return Uri.parse(databaseValue)
}
}
}
网友评论