Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to ignore primary key when I insert room database entity

I’m wondering how to ignore primary key when I insert some entity.
(Room Entity have to have more than 1 primary keys)
For example, there is an entity following under.

@Entity(primaryKeys = ["id"], tableName = "someEntity")
data class SomeEntity(
    val id: Int = 0,
    val someClass: SomeClass<*>? = null
)

the insert logic will be like this.

@Insert(onConflict = OnConflictStrategy.REPLACE)
abstract fun insert(obj: SomeClass): Completable

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In my project, when I have to insert SomeEntity with dao,
I can only get SomeClass<*>? type, without id: Int.
Does @AutoGenerate annotation on column id can solve my problem?
If "yes", please show me some simple example guys..!
Or if you guys have other ways to solve my problem, help me..!

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading