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

All we need is an easy explanation of the problem, so here it is.

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’

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

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.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply