Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Room @ForeignKey This annotation is not applicable to target member property with backing field when updating to 2.4.0

I have an issue when updating to Room 2.4.0-rc01 on fields annotated with @ForeignKey. This version adds an empty @Target in its definition making it impossible to target properties.

@Entity
class Foo {
    @PrimaryKey
    @ColumnInfo
    var id: String = ""

    @ForeignKey(entity = Foo::class, parentColumns = ["bar_id"], childColumns = ["bar"])
    @ColumnInfo
    var bar: String? = null
}

@Entity
class Bar {
    @PrimaryKey
    @ColumnInfo
    var bar_id: String = ""
}

I have the following error at the @ForeignKey annotation: This annotation is not applicable to target 'member property with backing field'

like image 892
Rubén Viguera Avatar asked Jan 24 '26 09:01

Rubén Viguera


1 Answers

I have found that annotations with an empty @Target can only be placed inside other annotations

So the solution is to move @ForeignKey inside @Entity as following:

@Entity(foreignKeys = [ForeignKey(entity = Bar::class, parentColumns = ["bar_id"], childColumns = ["bar"])])
class Foo {
    @PrimaryKey
    @ColumnInfo
    var id: String = ""

    @ColumnInfo
    var bar: String? = null
}

@Entity
class Bar {
    @PrimaryKey
    @ColumnInfo
    var bar_id: String = ""
}

Note that annotating a field even didn't work before. So a foreign key wasn't being created at all.

like image 171
Rubén Viguera Avatar answered Jan 26 '26 21:01

Rubén Viguera