architecture-components-samples icon indicating copy to clipboard operation
architecture-components-samples copied to clipboard

Room database build errors for @Ignore annotation

Open marianperca opened this issue 8 years ago • 7 comments

Hi,

I'm trying to use Room database within a Kotlin project, but I'm having issues with @Ignore annotation.

I have a data class and I'd like to ignore one field. If I add @Ignore to that field, when I build the project I get several errors saying: "Cannot find setter for field" and one: "Entities and Pojos must have a usable public constructor. You can have an empty constructor or a constructor whose parameters match the fields (by name and type)."

I've tried to add a new property within User class from GithubBrowserSample and when I build the project I get the same errors.

image

marianperca avatar Jul 23 '18 12:07 marianperca

What happened to this? I am experiencing the same problem.

jraedisch avatar Nov 29 '18 08:11 jraedisch

You should move the @Ignore field outside of the constructor, like this:

@Entity(primaryKeys = ["id"])
data class User(
        @field:SerializedName("id")
        val id: Int,

        @field:SerializedName("name")
        val name: String,
    
        @field:SerializedName("age")
        val age: Int
) {
    @Ignore
    val testme: String?
}

marianperca avatar Nov 29 '18 09:11 marianperca

@marianperca How do you set the testme field, then? Also, this does still seem like an issue. The documentation is literally incorrect.

MatthewTighe avatar Sep 19 '19 01:09 MatthewTighe

In my case the User class is fetched from an API, but the ignored field is not part of the data sent via API, so I have to set it manually when I need that data class.

marianperca avatar Sep 19 '19 06:09 marianperca

Right, but doesn't that cause the data class to become mutable? Wouldn't it need to be var testme: String??

I wanted to retain immutability, so I came up with the following solution:

@Entity(primaryKeys = ["id"])
data class User @Ignore constructor(
    @field:SerializedName("id")
    val id: Int,

    @field:SerializedName("name")
    val name: String,

    @field:SerializedName("age")
    val age: Int,

    @Ignore
    val testme: String?
) {
    constructor(id: Int, name: String, age: Int) : this(id, name, age, null)
}

This allows Room to have only a constructor that matches the fields of the entity.

MatthewTighe avatar Sep 19 '19 16:09 MatthewTighe

I was able to achieve the same result with @JvmOverloads, as recommended. But surely the docs need clarification.

gmk57 avatar May 25 '20 12:05 gmk57

This issue still persists in latest version of room with KSP room: 2.6.1

MiranKm avatar Oct 22 '24 09:10 MiranKm