开发者

Which tables must be defined as Discriminated Entities on Hibernate? [duplicate]

This question already has answers here: How to use Hibernate @Any-related annotations? (4 answers) How can I do bi-directional mapping over @Any annotated property? (2 answers) Closed 6 months ago.

I want to develop a blog and image gallery system. My db schema likes below;

IMAGE {table}  | ARTICLE{table}    | COMMENT{table}

-------------------|------------------------|-----------------------

PK id;              | PK id;                  &nbs开发者_StackOverflow中文版p; | PK id;

PATH String;   | FULLTEXT String  | ENTITY_ID {IMAGE_ID, ARTICLE_ID}

                       |                               | ENTITY_TYPE Enum{IMAGE,ARTICLE,COMMENT}

LIKES{table}  

------------------------------------------------------------------|

PK id;                                                                         |

ENTITY_ID {IMAGE_ID, ARTICLE_ID}                        |

ENTITY_TYPE Enum{IMAGE,ARTICLE,COMMENT}   |

So how can I create models? I think discriminated entities must be defined but which entities; Entity:SubClasses{IMAGE,ARTICLE} or Comment:SubClasses{ArticleComment, ImageComment}/Like:SubClasses{ImageLike,ArticleLike}?


You can use a discriminator column for different subclasses of entities are used when employing a Table per Hierarchy strategy. These use a single table with ALL the columns for each field in the table.

Continuing on this route:

So, if you are having an Image and an Article be subclasses of some shared entity, maybe a PostObject, your table would be along the lines of:

POST_OBJECT [Table]
-------------------
id
POST_TYPE (this is the discriminator column, defined as IMAGE, ARTICLE, COMMENT)
COMMENT_ID
PATH
FULLTEXT
... 

LIKES [Table] 
-------------------
id
POST_OBJECT_ID_fk

You could then have a foreign key to the POST_OBJECT id in your COMMENT table.

I would caution that you give appropriate consideration to your entity relationships. What you have above would most likely result in Comment, Article, Image, and Like objects.

What you have shown more closely resembles a Table per Concrete Class. Pro: More normalized layout Con: More joins

I would suggest checking the Hibernate documentation for the pros and cons of each so that you can make a more informed decision: http://docs.jboss.org/hibernate/core/3.5/reference/en/html/inheritance.html#inheritance-tableperclass

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜