Search code examples
sqlitenosqlrealmdata-modeling

Nosql database structure with Realm


I've a SQLite database to migrate to a Realm database.

It has, among others, an assoc table, a plant table and a definition table :

enter image description here

The assoc table associates two plants. The definition table cointains the name of the plant in different languages.

Since I use a Realm database mapped to my POJO objects I have a class mapped to my assoc table (the Realm equivalent). This assoc class contains two Lists for plant_id1 and plant_id2. The problem is that I must be able to retrieve all the assoc with all the plant but I must be able to find all distinct plants too without needing the assoc.... I guess there is something i didn't understand with data modeling using nosql... but how can I do this ? do I have to replicate my plants data in the assoc and an in a list of plants outside of assoc ? i'm not sure to be totally clear here...


Solution

  • I guess there is something i didn't understand with data modeling using nosql... but how can I do this ?

    public class Plant extends RealmObject {
        // PK
        RealmList<Plant> associatedPlants;
    
        @LinkingObjects("plant1")
        private final RealmResults<Assoc> assoc1 = null;
    
        @LinkingObjects("plant2")
        private final RealmResults<Assoc> assoc2 = null;
    
        @LinkingObjects("associatedPlants")
        private final RealmResults<Plant> associatedByPlants = null;
    }
    
    public class Assoc extends RealmObject {
        // PK
        Plant plant1;
        Plant plant2;
    }
    

    Your definition seems to be wrong, if you want multiple definitions to belong to the plant, then you can't have the definitionId in the plant. I'd most likely just have a field for each language name anyways.