Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply Room TypeConverter to a single field of an entity?

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
)

I get the error mentioned above.

The DateStringConverter class is:

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)
    }
}

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"

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?

like image 857
Lazar Avatar asked Aug 31 '25 02:08

Lazar


1 Answers

You must specify that the annotation should be applied to the field

@field:TypeConverters(DateStringConverter::class)
val date: Date

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 (constructor parameter);
  • property;
  • field.

https://kotlinlang.org/docs/reference/annotations.html#annotation-use-site-targets

like image 185
IR42 Avatar answered Sep 02 '25 16:09

IR42