Many-to-many and composite keys examples?

670 views
Skip to first unread message

José Román Bilbao Castro

unread,
May 14, 2015, 3:45:22 PM5/14/15
to realm...@googlegroups.com
Hi all,

Can anybody point me towards examples using both things (not necessarily together, I am looking for independent examples).

Thanks in advance,

Jose

Christian Melchior

unread,
May 17, 2015, 2:19:27 PM5/17/15
to José Román Bilbao Castro, realm...@googlegroups.com
Hi José

Realm currently doesn't support composite keys, so right now the workaround would be to create a calculated key you manually keep up to date whenever you change any of the composite key values:

public MyObj extends RealmObject {

@PrimaryKey
private String compositeKey;

private int int1;
private int int2;

// Getters and setters

public static String getCompositeKey(MyObj obj) {
return Integer.toString(obj.getInt1()) + Integer.toString(obj.getInt2());
}
}

realm.beginTransaction();
myObj.setInt1(42);
myObj.setInt2(43);
myObj.setCompositeKey(MyObj.getCompositeKey(myObj));
realm.commitTransaction();

This is not ideal and is something we want to fix. You can follow progress on that here: https://github.com/realm/realm-java/issues/1129


Regarding many-to-many relations, then you have to keep in mind that Realm is not a relational database, so the standard way of having to create a many-to-many table doesn't apply here. Instead you can just do the following:


public class Foo extends RealmObject {
private RealmList<Bar> bars;

public void setBars(ReamList<Bar> bars) {
this.bars = bars;
}

public RealmList<Bar> getBars() {
return bars;
}
}

public class Bar extends RealmObject {
private RealmList<Foo> foos;

public void setFoos(ReamList<Foo> foos) {
this.foos = foos;
}

public RealmList<Foo> getFoos() {
return foos;
}
}

I hope that can get you started.

--
Christian Melchior
Senior Android Developer


--
You received this message because you are subscribed to the Google Groups "Realm Java" group.
To unsubscribe from this group and stop receiving emails from it, send an email to realm-java+...@googlegroups.com.
To post to this group, send email to realm...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/realm-java/8e309bd4-0b5a-4e84-b4dc-bec6b64aa7e8%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



{#HS:90932673-1111#}
Reply all
Reply to author
Forward
0 new messages