JPA polymorphic oneToMany

后端 未结 4 2102
栀梦
栀梦 2020-12-19 11:44

I couldn\'t figure out how to cleanly do a tag cloud with JPA where each db entity can have many tags.

E.g

Post can have 0 or more Tags User can have 0 or mo

4条回答
  •  情歌与酒
    2020-12-19 12:47

    Is there a better way in JPA than having to make all the entities subclass something like Taggable abstract class?

    Let's forget the example :) JPA does support polymorphic associations but the target classes have to be part of an inheritance hierarchy. And here are some more rules of thumb about inheritance strategies:

    • SINGLE_TABLE:
      • All the classes in a hierarchy are mapped to a single table
      • This strategy provides good support polymorphic relationships between entities and queries that cover the entire class hierarchy.
      • May contain null fields for some subclass data
    • TABLE_PER_CLASS:
      • Each class in a hierarchy mapped to a separate table and hence, provides poor support for polymorphic relationships
      • requires SQL union or separate SQL queries for each subclass
    • JOINED
      • no null fields => compact data
      • This provides good support for polymorphic relationships, but requires one or more join operations – may result in poor performance

    In short, if your subclasses declare relatively few properties, prefer the SINGLE_TABLE strategy. If not, use a JOINED strategy unless you have a deep hierarchy (in which case the cost of joins may become more expensive than unions and then TABLE_PER_CLASS would be "less worse").

    References

    • JPA 1.0 Specification
      • Section 2.1.9 "Inheritance"
      • Section 2.1.10 "2.1.10 Inheritance Mapping Strategies"

提交回复
热议问题