Realm ORM: how to deal with Maps?

会有一股神秘感。 提交于 2019-11-30 15:17:05

问题


I am creating an Android app and I need to persist a Map<String,MyClass>. I've just started to use Realm ORM, as it supports one-to-one and one-to-many, enumerations and lists. I also found a workaround for lists of strings (i.e. I have to create a StringWrapper class encapsulating a string. However, from the documentation I understand there is no easy way like RealmMap, as it happens for lists. So, I'm looking for the best way to persist a map. My current idea is to replace my map with a list of objects KeyValueObject encapsulating a String (the former map key) and a MyClass. Similarly to Map.Entry. Is there any other solution that does not need me to rework the domain model for technology reasons?


回答1:


As you notice, Realm doesn't yet support maps: https://github.com/realm/realm-java/issues/759

You could use the model classes:

class MyData extends RealmObject {
    private RealmList<MyMapEntry> myMap;
}

class MyMapEntry extends RealmObject {
    private String key;
    private MyClass value;
}

Say you have a MyData object called myData and you wish to fetch the value associated with myKey, the query MyClass myClass = myData.getMyMap().where().equalTo("key", myKey).firstFirst() might be useful.




回答2:


Well, if you do have the luxury of reworking the persistence layer a bit, then the simplest solution is to not use a Map<String at all.

A Map<String literally means that a particular String is associated with one object. You can do the same thing just by having that String be part of your RealmObject. Then you can query based on that.

So any RealmResults` with a query for the string will contain one element, and that element will be the value of said map.



来源:https://stackoverflow.com/questions/35311755/realm-orm-how-to-deal-with-maps

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!