JPA 多态 oneToMany [英] JPA polymorphic oneToMany

查看:45
本文介绍了JPA 多态 oneToMany的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何用 JPA 干净地做一个标签云,其中每个 db 实体可以有很多标签.

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 中是否有比将所有实体子类化为可标记抽象类之类的更好的方法?一个 Tag 实体会引用许多 Taggables.

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:
    • 层次结构中的所有类都映射到一个表中
    • 该策略提供了良好的支持多态关系涵盖的实体和查询整个类层次结构.
    • 可能包含一些子类数据的空字段
    • 层次结构中的每个类都映射到一个单独的表,因此,提供对多态的支持很差关系
    • 每个子类需要 SQL 联合或单独的 SQL 查询
    • 没有空字段 => 压缩数据
    • 这为多态关系提供了很好的支持,但是需要一个或多个连接操作——可能会导致性能不佳

    简而言之,如果您的子类声明的属性相对较少,则更喜欢 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 多态 oneToMany的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆