Android Persistence Library: What is the best way to implement many relationships?

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

I am trying to implement the following many, many relationships:

enter image description here

Here are my classes Entity:

Person:

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

  @PrimaryKey
  public int id;

  public String name;

}

Grade Cat:

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

  @PrimaryKey
  public int id;

  public int age;

  public String name;

}

And the class PersonCat:

@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 to manipulate humans with cats in my application:

public final class RoomPersonWithAnimals {

  @Embedded
  public RoomPerson person;

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

}

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

Do I have to make 3 requests each time to save:

  • man at table Person
  • cats on the table Cat
  • his cats to the table PersonCat

Here is the Java code that illustrates 3 queries:

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, you can save only one request for this data. Is the room restriction, or is my implementation incorrect?

Thank you in advance for your help!

+4

Source: https://habr.com/ru/post/1682468/


All Articles