Storing inherited objects in a database

后端 未结 3 1838
长情又很酷
长情又很酷 2021-01-06 06:05

I\'m trying to figure out the best way to map inheritance relationships in an object model into a relational database. For example consider the following class structure.

3条回答
  •  感情败类
    2021-01-06 06:30

    If you are designing keeping the current classes in mind, i would prefer your option 3 as the preferred option for the reasons your stated above.

    Re your query about :

    However, I'm not sure how to create the relationship between the Items table and the
    Widgets and Doohickies tables. I don't want to end up with row in either table 
    referencing the same ItemID in the Items table. 
    

    Bill's suggestion above is definitely a good option. Something that i hadnt thought of :-) However, i was thinking that its a relationship that you can enforce either in your application code itself or by using an Insert trigger.

    My concern however is about trying to simulate the inheritance itself at the DB level.

    If the number of child classes is expected to grow over a period of time, then this kind of DB Design could become very difficult to maintain.

    In addition to :

    Items Table: ItemID (PK), Name, Size        
    Widgets Table: WidgetID (PK), ItemID (FK), Color        
    Doohicky Table: DoohickyID (PK), ItemID (FK), Smell        
    

    What is the likelyhood of new classes like the following getting added ?

    DontDoHicky Table : DoohickyID (PK), ItemID (FK), Smell, **TASTE**        
    MidWidget Table : WidgetID (PK), ItemID (FK), Color , **Height**        
    MidDoHicky Table : WidgetID (PK), ItemID (FK), **Height**, **Smell**
    

    This is of course the classic OO inheritance problem. If you expect the application to grow like this over a period of time and maybe need to plan for it beforehand, at a DB level, you might prefer go with a more generic approach

    Items Table: ItemID (PK), Name, Size, **ItemType**        
    **ItemAttributes Table : ItemID (PK), AttributeID, AttributeName, AttributeValue**    
    

    This will allow you to enforce your constraint of 1:1 mapping easily and allow your to easily query all attributes using the AttributeName as long as those are standard.

    This is probably the old-fashioned approach and not very object oriented but it might be more suitable based on future flexibility.

提交回复
热议问题