gpt4 book ai didi

java - 可嵌入和 ElementCollection 嵌套

转载 作者:搜寻专家 更新时间:2023-10-31 08:26:26 28 4
gpt4 key购买 nike

我有一个相当典型的场景,其中有一个主要的 @Entity 并且他内部的所有内容都是可嵌入的(因此没有父项,其中的所有内容都没有意义)。现在 JPA 2.0 阻止我将 @ElementCollection 嵌套在另一个 @ElementCollection 中定义的 @Embeddable 中:

JSR-317 2.6 Collections of Embeddable Classes and Basic Types An embeddable class (including an embeddable class within another embeddable class) that is contained within an element collection must not contain an element collection, nor may it contain a relationship to an entity other than a many-to-one or one-to-one relationship

现在的问题是:这是为什么?一个简单的例子:

@Entity
public class Tournament {
@Id
Long id;

@ElementCollection
@CollectionTable
private List<Edition>;
}

@Embeddable
public class Edition {

@ElementCollection
@CollectionTable
private List<Round>
}

@Embeddable
public class Round {

blabla;
}

这有什么问题?这只是一个示例,您可以将 Round 和 Edition 定义为 Entity 并解决问题,但在我的例子中,由于多种原因,我需要强制执行没有他的 parent ,非常嵌套的东西没有意义。

为什么 JPA 2.0 必须阻止我这样做?

最佳答案

您的情况违反了您粘贴的规范元素:

Edition 本身就是@Embeddable,并且包含一个Round 的元素集合,因此:

包含在元素集合 (Tournament.editions) 中的可嵌入类 (Edition) 不得包含元素集合 (Edition.rounds)。

至于为什么你不能这样做 - 如果你看一下来自 http://en.wikibooks.org/wiki/Java_Persistence/ElementCollection 的例子然后你会看到 child (版本)将只用一个 FK 映射回所有者(Tournament.id)而没有自己的 ID 列 - 因为作为一个弱实体,它没有自己的 ID自己的,并且仅通过引用锦标赛的 ID 来定义。

以 Round 为例,如果它也是一个弱实体,那么它应该由 FK 引用版本定义 - 但我们已经说过它没有自己的 ID,所以你不能在没有它的情况下将它映射到数据库中向 Edition 添加一个 ID - 此时它本身就是一个实体,而不仅仅是 @Embeddable。

查看下面评论中的维基百科示例 - http://en.wikipedia.org/wiki/Weak_entity - 弱实体的例子有 OrderNumber、CustomerNumber 等 - 只有嵌入到另一个对象中才有意义的东西。

您仍然可以拥有具有父映射(即版本上的锦标赛引用)和/或双向引用的实体。您可以使用 @ManyToOne 注释上的 nullable=false 属性强制在 Edition 上定义父级,从而强制执行模型的要求。

关于java - 可嵌入和 ElementCollection 嵌套,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22126397/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com