JPA多态的oneToMany [英] JPA polymorphic oneToMany
问题描述
我不知道如何使用JPA干净地制作标签云,其中每个数据库实体可以具有许多标签.
I couldn't figure out how to cleanly do a tag cloud with JPA where each db entity can have many tags.
例如
帖子可以有0个或更多标签 用户可以有0个或更多标签
Post can have 0 or more Tags User can have 0 or more Tags
在JPA中,是否有比必须使所有实体子类(例如Taggable抽象类)更好的方法?标签实体引用多个标签的地方.
Is there a better way in JPA than having to make all the entities subclass something like Taggable abstract class? Where a a Tag entity would reference many Taggables.
标签云只是一个示例,用于简化我遇到的问题.在我的场景中,该关系应为OneToMany,其中标签无法重用.
the tag cloud is just a sample to simplify the problem I am having. In my scenario, the relation should be OneToMany where a Tag cannot be reused.
谢谢
推荐答案
在JPA中,有没有比使所有实体成为子类(如Taggable抽象类)更好的方法?
Is there a better way in JPA than having to make all the entities subclass something like Taggable abstract class?
让我们忘记这个示例:) JPA确实支持多态关联,但是目标类必须是继承层次结构的一部分.以下是有关继承策略的更多经验法则:
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:
- 层次结构中的所有类都映射到单个表
- 此策略为之间的多态关系提供了良好的支持 涵盖以下内容的实体和查询 整个类的层次结构.
- 可能包含某些子类数据的空字段
- 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
- 层次结构中的每个类都映射到单独的表,因此提供了 对多态性的支持不佳 关系
- 为每个子类需要SQL联合或单独的SQL查询
- 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
- 没有空字段=>紧凑数据
- 这为多态关系提供了良好的支持,但是 需要一个或多个联接操作– 可能会导致效果不佳
- no null fields => compact data
- This provides good support for polymorphic relationships, but requires one or more join operations – may result in poor performance
简而言之,如果子类声明的属性相对较少,则首选SINGLE_TABLE
策略.如果不是这样,请使用JOINED
策略,除非您具有较深的层次结构(在这种情况下,连接的成本可能比联合的成本更高,然后TABLE_PER_CLASS
的情况会更糟").
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").
- JPA 1.0规范
- 第2.1.9节继承"
- 第2.1.10节"2.1.10继承映射策略"
- JPA 1.0 Specification
- Section 2.1.9 "Inheritance"
- Section 2.1.10 "2.1.10 Inheritance Mapping Strategies"
这篇关于JPA多态的oneToMany的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!