领域ORM:如何处理地图? [英] Realm ORM: how to deal with Maps?
问题描述
我正在创建一个Android应用,并且需要保持Map<String,MyClass>
.
我刚刚开始使用领域ORM ,因为它支持一对一和一对多,枚举和列表.我还找到了字符串列表的解决方法(即,我必须创建一个封装字符串的StringWrapper类.
但是,根据文档,我知道没有像RealmMap
这样的简单方法用于列表.
因此,我正在寻找保留地图的最佳方法.
我当前的想法是用封装了String
(以前的映射键)和MyClass
的对象KeyValueObject
列表代替我的地图.与 Map.Entry
相似.
出于技术原因,是否还有其他不需要我重新设计域模型的解决方案?
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?
推荐答案
As you notice, Realm doesn't yet support maps: https://github.com/realm/realm-java/issues/759
您可以使用模型类:
class MyData extends RealmObject {
private RealmList<MyMapEntry> myMap;
}
class MyMapEntry extends RealmObject {
private String key;
private MyClass value;
}
假设您有一个名为myData
的MyData
对象,并且希望获取与myKey
关联的值,则查询MyClass myClass = myData.getMyMap().where().equalTo("key", myKey).firstFirst()
可能会有用.
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.
这篇关于领域ORM:如何处理地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!