Search code examples
androidandroid-roomandroid-architecture-components

Android Room table with unique on replace constraint


I am in the process of migrating my app to use Room and need a little help figuring out how to annotate one of my tables correctly.

The existing SQL script looks like this:

CREATE TABLE member_rooms (
   _id INTEGER PRIMARY KEY AUTOINCREMENT,
   new_messages INTEGER DEFAULT 0,
   member_id_fk TEXT,
   FOREIGN KEY ( member_id_fk ) REFERENCES members ( member_id ) ON DELETE CASCADE,
   UNIQUE ( member_id ) ON CONFLICT REPLACE )

My new Entity class is as follows:

@Entity(tableName = "member_rooms",
        indices = {@Index(value = {"member_id_fk"}, unique = true)},
        foreignKeys = {@ForeignKey(entity = MemberTableModel.class,
              parentColumns = "member_id",
              childColumns = "member_id_fk",
              onDelete = CASCADE)})
public class MemberRoomTableModel {
    @PrimaryKey(autoGenerate = true)
    @NonNull
    @ColumnInfo(name = "_id")
    private int rowId;

    @ColumnInfo(name = "new_messages")
    private int numNewMessages;

    @ColumnInfo(name = "member_id_fk")
    private String memberId;

   .... constructors getters etc ... }

I believe this is the correct representation of this table but the ON CONFLICT REPLACE constraint is what is throwing me off. Since Room uses SupportSqlOpenHelper/Database the new wrapper APIs include the conflict strategy in them at the time of query. Does this replace the constraint on the table? Do my DAOs now need to handle the conflict on each of the queries? Or is there a field to annotate that replace in the Entity that I'm missing?


Solution

  • Annotate all your DAO method's with OnConflictStrategy , entity does not provide such an opportunity.