Shoaib Anwar
Shoaib Anwar

Reputation: 1625

Primary key from parent class using Room?

I am using Android Architecture Components. Hence using Room 'ORM'. I have a class EQPreset that has a member String presetName. This class has a child class called UserDefinedEQPreset and it contains an int[] arr. I have declared the child class EQPreset and entity using @Entity annotation, since only this subtype I want to store in db. Now I want to use parent class's (EQPreset) member String presetName to be used as primary key. How to declare a member of parent class as primary key while using Room. I know @Primarykey annotation is used to declare the primary key. But how to use parent class's member as primary key.

Upvotes: 4

Views: 2653

Answers (2)

Edwin Nyawoli
Edwin Nyawoli

Reputation: 856

@Entity(primaryKeys = ["presetName"])
class UserDefinedEQPreset extends EQPreset{
    ...
}

I think this is what you're looking for. Use the primaryKeys attribute on the Entity annotation to specify the primary key. You can also use this to specify composite primary keys.

Upvotes: 1

CommonsWare
CommonsWare

Reputation: 1007658

Put the @PrimaryKey annotation on the parent class' field. Done.

For example, in this sample app, I have an abstract class Plan with @PrimaryKey public final String id. All subclasses, such as Trip, inherit that @PrimaryKey definition.

Not everything inherits properly (e.g., @TypeConverters works on fields but not on classes), but @PrimaryKey seems to.

Upvotes: 6

Related Questions