Search code examples
androidprimary-keyandroid-roomandroid-architecture-components

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.


Solution

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