开发者

inheritance in document database?

开发者 https://www.devze.com 2023-01-03 05:39 出处:网络
I am wondering because I searched the pdf \"[noSql] the definitive guide\" and \"beginning [noSql]\" for the word \"inheritance\" but I didn\'t find anyt开发者_StackOverflow中文版hing? am I missing so

I am wondering because I searched the pdf "[noSql] the definitive guide" and "beginning [noSql]" for the word "inheritance" but I didn't find anyt开发者_StackOverflow中文版hing? am I missing something? because I'm doing a tablePerHierarchy inheritance with hibernate and mysql, does that become deprecated for some reason in [noSql]?

(replace [noSql] with the "not only sql" database you like)


I know this answer is a little late, but for MongoDB, you're probably looking at something slightly different.

Mongo is schemaless, so the concept of "tablePerHierarchy" is not necessarily useful.

Assume the following

class A
  property X
  property Y
  property Z

class B inherits from A
  property W

In an RDMS you would probably have something like this

table A: columns X, Y, Z
table B: columns X, Y, Z, W

But MongoDB does not have a schema. So you do not need to structure data in this way. Instead, you would have a "collection" containing all objects (or "documents") of type A or B (or C...).

So your collection would be a series of objects like this:

{"_id":"1", "X":1, "Y":2, "Z":3}
{"_id":"2", "X":5, "Y":6, "Z":7, "W":6}

You'll notice that I'm storing objects of type A right beside objects of type B. MongoDB makes this very easy. Just pull up a Document from the Collection and it "magically" has all of the appropriate fields/properties.

However, if you have "data objects" or "entities", you can make your life easier by adding a type.

{"_id":"1", "type":"A", "X":1, "Y":2, "Z":3}
{"_id":"2", "type":"B", "X":5, "Y":6, "Z":7, "W":6}

This makes it easier to write a factory class for loading your objects.


Well it's a pretty old question, but since I ended up here I'd like to add a 2017 update.
If your using mongoose to connect to MongoDb you may want to check out discriminators:

Discriminators are a schema inheritance mechanism. They enable you to have multiple models with overlapping schemas on top of the same underlying MongoDB collection.

Documentation was a little bit vague for me at first, this article could be a better place to grasp the idea.

0

精彩评论

暂无评论...
验证码 换一张
取 消