如何将Room TypeConverter应用于实体的单个字段? [英] How to apply Room TypeConverter to a single field of an entity?
问题描述
我一直在尝试将TypeConverter
应用于Room数据库实体的单个字段的不同解决方案,但出现错误
I have been trying different solutions for applying a TypeConverter
to a single field of a Room database entity but I am getting an error
Cannot figure out how to save this field into database. You can consider adding a type converter for it.
当我将转换器应用于这样的实体时:
When I apply the converter to the entity like this:
@Entity(tableName = DBKey.calendarDayTable)
@TypeConverters(DateStringConverter::class)
data class CalendarDay(
@PrimaryKey
val date: Date
)
一切正常,但是当我将其应用于这样的领域时:
everything works as expected, but when I apply it to the field like this:
@Entity(tableName = DBKey.calendarDayTable)
data class CalendarDay(
@PrimaryKey
@TypeConverters(DateStringConverter::class)
val date: Date
)
我收到上述错误.
DateStringConverter
类为:
class DateStringConverter {
private val formatter = SimpleDateFormat("yyyy-MM-dd")
@TypeConverter
fun dateFromString(value: String): Date {
return formatter.parse(value)!!
}
@TypeConverter
fun dateToString(date: Date): String {
return formatter.format(date)
}
}
我正在使用Room版本2.2.5
,并用Kotlin编写应用程序.
Room的依赖项为:
I am using the Room version 2.2.5
and writing the app in Kotlin.
The dependencies for Room are:
implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version"
implementation "androidx.room:room-ktx:$room_version"
是否可以仅将DateStringConverter
应用于CalendarDay
实体的date
字段,还是必须将其应用于整个实体?
Is there a way that I can apply DateStringConverter
only to the date
field of the CalendarDay
entity, or do I have to apply it to the whole entity?
推荐答案
您必须指定将注释应用于字段
You must specify that the annotation should be applied to the field
@field:TypeConverters(DateStringConverter::class)
val date: Date
如果未指定使用场所目标,则根据所使用注释的@Target注释选择目标.如果有多个适用目标,则使用以下列表中的第一个适用目标:
If you don't specify a use-site target, the target is chosen according to the @Target annotation of the annotation being used. If there are multiple applicable targets, the first applicable target from the following list is used:
- param(构造函数参数);
- 财产;
- 字段.
- param (constructor parameter);
- property;
- field.
https://kotlinlang.org/docs/reference /annotations.html#annotation-use-site-targets
这篇关于如何将Room TypeConverter应用于实体的单个字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!