Skip to content
Advertisement

Android Room Persistence Library : What is the best way to implement a many to many relation?

I used to use Realm and I am currently testing Room in order to compare both tools.

I am trying to implement the following many to many relation :

enter image description here

Here my Entity classes :

The Person :

@Entity(tableName = "person")
public final class RoomPerson {

  @PrimaryKey
  public int id;

  public String name;

}

The Cat class :

@Entity(tableName = "cat")
public final class RoomCat {

  @PrimaryKey
  public int id;

  public int age;

  public String name;

}

And the PersonCat class :

@Entity(tableName = "person_cat", primaryKeys = { "personId", "catId" },
    indices = { @Index(value = { "catId" }) },
    foreignKeys = { @ForeignKey(entity = RoomPerson.class, parentColumns = "id", childColumns = "personId"),
        @ForeignKey(entity = RoomCat.class, parentColumns = "id", childColumns = "catId") })
public final class RoomPersonCat {

  public int personId;

  public int catId;

  public RoomPersonCat(int personId, int catId)  {
    this.personId = personId;
    this.catId = catId;
  }

}

I also have a POJO in order to manipulate a person with cats into my app :

public final class RoomPersonWithAnimals {

  @Embedded
  public RoomPerson person;

  @Relation(parentColumn = "id", entityColumn = "id", entity = RoomCat.class)
  public List<RoomCat> cats;

}

The question is : how to save a List<RoomPersonWithAnimals> ?

Should I do 3 requests each time in order to save :

  • the person into the table Person
  • the cats into the table Cat
  • its cats into the table PersonCat

Here the java code that illustrate the 3 requests :

for (RoomPersonWithAnimals personWithAnimals : persons) {
  myRoomDatabase.roomPersonDao().insert(personWithAnimals.person);
  myRoomDatabase.roomCatDao().insertAll(personWithAnimals.cats.toArray(new RoomCat[personWithAnimals.cats.size()]));

  for (RoomCat cat : personWithAnimals.cats) {
    myRoomDatabase.roomPersonCatDao().insert(new RoomPersonCat(personWithAnimals.person.id, cat.id));
  }
}

In Realm, it’s possible to save in only one request these data. Is is a limitation of Room or my implementation is wrong ?

Thank you in advance for your help !

Advertisement

Answer

Since Room 2.2, the ORM support all possible relations between tables.

See the dedicated article on medium: Database relations with Room

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement