java Hibernate 映射超类关系和覆盖

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3227854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 00:53:34  来源:igfitidea点击:

Hibernate Mapped Superclass relationships and overriding

javahibernateannotations

提问by Andrew

I have an abstract MappedSuperClass, Participant, which is extended by three kinds of 'Participant'. Each one then uses its own kind of 'Project', also an abstract MappedSuperClass. However, I want the base class to know about Projects so I can write generic code to interact with Participants. How do I specify this using Hibernate annotations? and how will I override it in the ExtendedParticipant and ExtendedProject classes?

我有一个抽象的 MappedSuperClass,Participant,它由三种“Participant”扩展。然后每个人都使用自己的“项目”类型,也是一个抽象的 MappedSuperClass。但是,我希望基类了解项目,以便我可以编写通用代码与参与者进行交互。我如何使用 Hibernate 注释指定它?以及如何在 ExtendedParticipant 和 ExtendedProject 类中覆盖它?

Each Participant type, and each Project type, have their own database tables with existing data and ids (not unique across tables) that I cannot change.

每个 Participant 类型和每个 Project 类型都有自己的数据库表,其中包含我无法更改的现有数据和 ID(跨表不唯一)。

The following code gives me the IDE error "Many to one attribute should not be 'Mapped Superclass'".

下面的代码给了我 IDE 错误“多对一属性不应该是‘映射超类’”。

@MappedSuperclass
public abstract class Participant implements Persistable {

    ...

    @ManyToOne
    @JoinColumn(name = "project_id")
    public Project getProject() {
        return project;
    }

    public void setProject(Project project) {
        this.project = project;
    }

    ...
}

and the Project class is much the same with the same problem:

并且 Project 类与相同的问题大致相同:

@MappedSuperclass
public abstract class Project implements Persistable {

    ...

    @OneToMany
    public List<Participant> getParticipants() {
        return participants;
    }

    public void setProject(List<Participant> participants) {
        this.participants = participants;
    }

    ...
}

采纳答案by Pascal Thivent

A mapped superclass is not an Entity, it can't be part of an association. So map your classes as entities and either introduce a mapped superclass "above" them or use a TABLE_PER_CLASSstrategy.

映射的超类不是实体,它不能是关联的一部分。因此,将您的类映射为实体,并在它们的“上方”引入映射的超类或使用TABLE_PER_CLASS策略。

See also

也可以看看

回答by roshi

Seems possible to have relations defined through the mappedsuperclass according to the following

似乎可以根据以下内容通过映射超类定义关系

回答by JeSa

Docs said it's possible, but superclass isn't abstract in example https://docs.oracle.com/javaee/5/api/javax/persistence/MappedSuperclass.html

文档说这是可能的,但超类在示例中不是抽象的 https://docs.oracle.com/javaee/5/api/javax/persistence/MappedSuperclass.html