4

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 !

rolandl
  • 1,769
  • 1
  • 25
  • 48
  • 2
    Room is troublesome because of its lack of POJO relations. I suggest don't go for it at all or wait for them to include Realm like facilities. Realm has its own limitations as of now. It really bothers me that why can't someone come up with a complete solution 10 years from the first android release. Something like CoreData. Realm's problem is that it asks us to implement a RealmObject. Room's problem is that it doesn't understand relations inside an Object. – Muhammad Ahmed AbuTalib Sep 10 '17 at 07:51
  • This might be helpful https://stackoverflow.com/a/58424784 – Nischal Oct 21 '19 at 04:55

1 Answers1

0

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

See the dedicated article on medium: Database relations with Room

rolandl
  • 1,769
  • 1
  • 25
  • 48