Many-to-many relationship in Android-Realm (n-to-m)

I need to simulate a many-to-many (n: m) relationship with Realm in Android.
For example, A Country

has many Rivers

, but there are also Rivers

many that pass through Countries

.
I need to query both ways.

As read here , we should avoid these CountryToRiver(int cId, int rId)

helper classes known from SQL. Instead, Christian suggested bi-directional reference — sounds good.

I am currently getting data (JSON) and relations inside rivers like this: getCountries: [{"id":"1", "name":"Dreamland"}, ...]


getRivers:[{"id":"42", "name":"Wateryriver", "length":"5000", "countryIds":[1,2,5]}, ...]

So what I ended up with works, but I'm not sure if this is the best way or it might be a mistake / easier:

Country.java

:

@PrimaryKey
private int id;
private String name;
private RealmList<River> riverRealmList; // not exposed to GSON
// getter & setter

      

River.java

:

@PrimaryKey
private int id;
private String name;
private int length;
@Ignore // ignored by realm
private List<Integer> countryIds;
private RealmList<Country> countryRealmList; // not exposed to GSON
// getter & setter

      

Main.java

:

public void saveData(List<Country> countries, List<River> rivers) { // lists via GSON
  for(Country c : countries) {
    realm.copyToRealmOrUpdate(c); // save countries normally
  }

  for(River r : rivers) {
    buildRelationshipAndSave(r);
  }
}


public void buildRelationshipAndSave(River river) {
  for (int id : river.getCountryIds) {

    // get country with this id from realm and add it to the river countrylist
    Country realmCountry = realm.where(Country.class).equalTo("id", id).findFirst();
    if(realmCountry!=null)
        river.getContryRealmList().add(realmCountry); //<- is this list access dangerous??

    // until here it was a POJO, now store it in realm
    River realmRiver = realm.copyToRealmOrUpdate(river);

    // now add this river to the country riverlist, too, if not already existent
    if (!realmCountry.getRiverRealmList().contains(realmRiver))
        realmCountry.getRiverRealmList().add(realmRiver);
  }
}

      

Do you have any improvements or comments on this?
Thanks in advance!

+3


source to share





All Articles