a field name “ClassName” is being inserted into mongodb by morphia

自闭症网瘾萝莉.ら 提交于 2019-11-28 00:10:43

问题


I'm pretty new to mongodb and morphia, after starting using it, I realize that there is a extra part in mongodb document, the record contains a filed name "ClassName" with value of the class that morphia mapped.

{ "_id" : ObjectId("51e7a85e300441e5885316c0"), "className" : "models.User", "imgurl" : "", "uname" : "alex"}

is this normal? i feel it is violating the integrity of the data in the db, is there anyway to get around it?


回答1:


You can explicitly disable the className attribute: @Entity(noClassnameStored = true)

I'm generally suppressing the attribute, if there is a single entity class. If I'm subclassing my entity, I'm explicitly enabling it (which is the default, but just to be sure).

If I'm not mistaken, Morphia is clever enough to guess the correct subclass based on the properties even if there is no className (based on reflection). So if you have an attribute mongoKnowledge in your subclass Developer of Person and your subclass Manager doesn't have it, Morphia will know that documents with mongoKnowledge must be of the class Developer. So strictly speaking className is only required if your subclasses have the same attributes; however, I wouldn't rely on it too much.

I haven't tried to rename the entity classes, but it will probably cause issues. There's a long standing issue to provide a @Polimorphic annotation and to fix it together with that. See https://code.google.com/p/morphia/issues/detail?id=22




回答2:


This is normal. Since Morphia supports Polymorphism, means subclasses shall be stored in the same collection where the super class is persisted. In order to differentiate/ filter while querying and storing, it uses this field. Hope you would use Morphia for querying also. How do you think, it affects the integrity of your data, as you could easily filter it out.

Hibernate too, has discriminator column for supporting polymorphism.

http://docs.jboss.org/hibernate/core/3.3/reference/en/html/mapping.html#mapping-declaration-discriminator



来源:https://stackoverflow.com/questions/17719018/a-field-name-classname-is-being-inserted-into-mongodb-by-morphia

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