Search code examples
androidentityandroid-roomprimary-keyandroid-room-relation

How to ignore primary key when I insert room database entity


How do I ignore the primary key when I insert some entity?

Room Entity has to have more than 1 primary key.
For example, there is an entity following under.

@Entity(primaryKeys = ["id"], tableName = "someEntity")
data class SomeEntity(
    val id: Int = 0,
    val someClass: SomeClass<*>? = null
)
@Insert(onConflict = OnConflictStrategy.REPLACE)
abstract fun insert(obj: SomeClass): Completable

Parameter "obj" will have two column(fields).
When I have insert logic like that,
do I have to care about id (with autoGenerate annotation) column?

When I insert SomeEntity with dao,
I can only get SomeClass<*>? type, without id: Int.
Does @AutoGenerate annotation on column id can solve my problem?


Solution

  • Room understands val id: Int = 0 if it is marked with @PrimaryKey as a value to be ignored when inserting.

    @Entity
    data class SomeEntity(
        @PrimaryKey(autoGenerate = true)
        val id: Int = 0,
        val someClass: SomeClass<*>? = null
    )
    

    and when creating a new instance SomeEntity(someClassInstance) is completely fine.

    Note: if SomeClass isn't a basic class that SQL is able to save, you need to have some way to serialize it.