Search code examples
javaandroidandroid-roomprimary-key

How to override a PrimaryKey in Android Room entity


I'm new for the Android Room library. I use Room database to store configuration data for my application. I have two classes declared as @Entity : Operation and OperationType.

Operation extends OperationType super class. OperationType has a member declared as @PrimaryKey : operation

I'd like to define a new @PrimaryKey in Operation class, but at this point, I obtain an error during compilation : compil err

I don't understand why this error appears and what i'm doing wrong. According to Room documentation, override is possible : PrimaryKey  |  Android Developers. Any idea or suggestion will be appreciated :)


Solution

  • I've got a feeling that this some sort of bug in that it should probably only be a warning.

    At first I was getting the issue, testing it using another answer. I then got it to compile OK by right clicking the message and disabling Show Warnings.

    • if you clean the project it reappears.

    Under all tried circumstances Room still generates the createAllTables method in the class named the same as the @Database annotated class suffixed with _Impl (in the generated java), that includes both tables as e.g. :-

        _db.execSQL("CREATE TABLE IF NOT EXISTS `OperationType` (`operationTypeId` INTEGER NOT NULL, PRIMARY KEY(`operationTypeId`))");
        _db.execSQL("CREATE TABLE IF NOT EXISTS `Operation` (`operationId` INTEGER, `operationTypeId` INTEGER NOT NULL, PRIMARY KEY(`operationId`))");
    
    • I have literally used the classes as shown so just the single member variable (however note that it only changes the primary key the member variable operationTypeId member variable is still copied from the super class).

    Furthermore actually running the App and forcing database access and doing nothing else, then the result is a database that contains both tables:-

    enter image description here