Android-Realm中的多对多关系(n-to-m)

时间:2015-05-22 08:35:04

标签: android orm many-to-many relationship realm

我需要在Android中模拟与Realm的多对多(n:m)关系 例如,一个Country有很多Rivers,但也有Rivers,它流经许多Countries
我需要向两个方向查询。

在阅读here时,我们应该避免从SQL中已知的这些CountryToRiver(int cId, int rId) 帮助程序类。相反,克里斯蒂安建议提到双向 - 听起来不错。

目前,我正在获取数据(JSON)以及河流内的关系,如下所示:
getCountries:[{"id":"1", "name":"Dreamland"}, ...]
getRivers:[{"id":"42", "name":"Wateryriver", "length":"5000", "countryIds":[1,2,5]}, ...]

所以我最终得到的是作品,但我不确定这是否是最好的方式,或者它是否可能是错误的/更容易:

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's 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's riverlist, too, if not already existent
    if (!realmCountry.getRiverRealmList().contains(realmRiver))
        realmCountry.getRiverRealmList().add(realmRiver);
  }
}

您对此有任何改进或评论吗? 提前谢谢!

0 个答案:

没有答案