當存儲對象類中使用了除String、Int 妻顶、Long等類型以外的復雜類型時候酸员,objectBox的處理方法:
實現(xiàn)一個objectBox的PropertyConverter接口的類,將復雜類型處轉(zhuǎn)換為基礎類型
實體類
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 不存放到數(shù)據(jù)庫
// 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)"
}
}
轉(zhuǎn)換處理類
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)
}
}
}