Search code examples
javaandroidkotlinandroid-room

Room @Ignore annotation not working with KSP


We are trying to ignore a field in constructor of data class

@Entity(tableName = "SampleEntityTable")
data class SampleEntity(
    @PrimaryKey(autoGenerate = true)
    val id: Int = 0,
    @Ignore
    var sampleJavaClass: SampleJavaClass,
    var epoch: Long = 0
)

SampleJavaClass is a class written in Java, the build fails with error:

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).
Tried the following constructors but they failed to match:
<init> -> [param:id -> matched field:id, param:sampleJavaClass -> matched field:unmatched, param:epoch -> matched field:epoch]

Solution

  • As you are Ignoreing the sampleJavaClass field, Room needs a constructor that takes just the id and epoch fields (i.e. those extracted from the database columns actually stored (not ignored)) as the sampleJavaClass field is not available when building SampleEntity objects when extracting data from the database.

    For example if SampleJavaClass were:-

    data class SampleJavaClass(
        var sjcid: Long,
        var sjctext: String
    )
    
    • included so that the concept can be proven by compiling (as shown below)

    Then you could modify the SampleEntity data class to be:-

    @Entity(tableName = "SampleEntityTable")
    data class SampleEntity(
        @PrimaryKey(autoGenerate = true)
        val id: Int = 0,
        @Ignore
        var sampleJavaClass: SampleJavaClass,
        var epoch: Long = 0
    ) {
        constructor(id: Int = 0, epoch: Long =0) : this(id = id, sampleJavaClass = SampleJavaClass(0,""), epoch = epoch)
    }
    
    • Here you can see that the additional constructor only takes the id and epoch parameters to build a SampleEntity object.

    Now if the constructor is commented out then compiling results in:-

    enter image description here

    Uncomment and:-

    enter image description here

    of course you have to consider the requirements for constructing the SampleJavaClass object when extracting from the database, which may alter exactly what constructor to utilise.