Search code examples
androidmysqldatabaserealmrealm-java

I'm using realm DB and it has no Foreign keys .. is there any alternative solution?


guys i'm working on a android project for my DB course and i'm using realm DB but the problem is that i just found that realm has no foreign keys(realm is NOT a relational DB) so i was wondering if there is any other solution to use as a foreign key?

i was thinking about using class composition but would it work ?


Solution

  • Realm has the concept of "relationships" (otherwise called as "links").

    To-one relationship:

    public class A extends RealmObject {
        B b;
    }
    

    To many relationship:

    public class A extends RealmObject {
        RealmList<B> bs;
    }
    

    And for either of those relationships, there exists an inverse relationship (Realm Java 3.5.0+)

    public class A extends RealmObject {
        B b;
    
        RealmList<B> bs;
    }
    
    public class B extends RealmObject {
        @LinkingObjects("b")
        private final RealmResults<B> fromB = null;
    
        @LinkingObjects("bs")
        private final RealmResults<B> fromBs = null;
    }
    

    If an object is unmanaged, then insertOrUpdate()/copyToRealmOrUpdate() will insert both A and its instance B into the Realm.

    If an object is managed, then the object you set as value must be managed as well.

    A a = realm.createObject(A.class);
    a.setB(realm.createObject(B.class)); // or copyToRealmOrUpdate(b) or .findFirst() etc