0

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?

philipxy
  • 14,867
  • 6
  • 39
  • 83
  • I almost want to say yes but I am not sure what is your problem. – TheLibrarian Oct 31 '22 at 14:31
  • @TheLibrarian when I have to insert `SomeEntity` with DAO, `SomeEntity` have two fields (id and someClass). But I can only get `SomeClass` property from server. the insert logic will be like this. @Insert(onConflict = OnConflictStrategy.REPLACE) { abstract fun insert(obj: SomeClass) } parameter "obj" will have two column(fields). The problem that I think is when I have insert logic like that, do I have to care about "id"(with autoGenerate annotation) column? – Hello World Oct 31 '22 at 14:41
  • Please ask 1 clear specific researched non-duplicate question. Debug questions require a [mre]. Please clarify via edits, not comments. [ask] [Help] – philipxy Nov 01 '22 at 00:53

1 Answers1

2

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.

TheLibrarian
  • 1,540
  • 1
  • 11
  • 22