Search code examples
androidkotlinandroid-room

How to extend class in Kotlin while using Room?


I have two data class Product and ProductInfo, ProductInfo is an extention of Product but how it should be writtein in Kotlin by using Room as if i try to use interface instead data class on Product i'm unable to set the @PrimaryKey annotation?

@Entity(tableName = "articoli")
data class Articoli (
    @PrimaryKey
    var codiceArticolo: String,
    var descrizione: String,
    var prezzoVendita: Float,
    var prezzoAcquisto: Float,
    var unitaMisura: String,
)

data class InfoArticoli(
    var codiceArticolo: String,
    var descrizione: String,
    var prezzoVendita: Float,
    var prezzoAcquisto: Float,
    var unitaMisura: String,
    var giacenza: List<String>,
    var famiglia: String,
    var reparto: String,
    var repartoCassa: String,
    var scortaMinima: String,
    var iva: String,
    var fornitore: String,
)

Solution

  • You can use the primaryKeys parameter of the @Entity annotation to specify specific primary keys.

    I suspect that what you want is :-

    data class Articoli (
        var codiceArticolo: String,
        var descrizione: String,
        var prezzoVendita: Float,
        var prezzoAcquisto: Float,
        var unitaMisura: String,
    )
    
    @Entity(tableName = "articoli", primaryKeys = ["codiceArticolo"])
    data class InfoArticoli(
        @Embedded
        var articoli: Articoli,
        var giacenza: List<String>,
        var famiglia: String,
        var reparto: String,
        var repartoCassa: String,
        var scortaMinima: String,
        var iva: String,
        var fornitore: String,
    )
    
    • where @Embedded effectively extends the Articoli
    • noting that you will have ongoing issues with giacenza as you either need a type converter or from a database perspective a table for the giacenza list.