java JPA 映射接口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/281503/
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-29 11:45:37  来源:igfitidea点击:

JPA mapping interfaces

javahibernateormjpainterface

提问by Paul Whelan

I am having trouble creating a mapping when the List type is an interface. It looks like I need to create an abstract class and use the discriminator column is this the case? I would rather not have to as the abstract class will just contain an abstract method and I would rather just keep the interface.

当 List 类型是接口时,我无法创建映射。看起来我需要创建一个抽象类并使用鉴别器列是这种情况吗?我宁愿不必因为抽象类只包含一个抽象方法而我宁愿只保留接口。

I have an interface lets call it Account

我有一个接口可以叫它帐户

public interface Account {
 public void doStuff();
}

Now I have two concrete implementors of Account OverSeasAccount and OverDrawnAccount

现在我有 Account OverSeasAccount 和 OverDrawnAccount 的两个具体实现者

public class OverSeasAccount implements Account {
 public void doStuff() {
   //do overseas type stuff
 }
}

AND

public class OverDrawnAccount implements Account {
 public void doStuff() {
   //do overDrawn type stuff
 }
}

I have a class called Work with a List

我有一个名为“使用列表工作”的课程

private List<Account> accounts; 

I am looking at discriminator fields but I seem to be only able do this for abstract classes. Is this the case? Any pointers appreciated. Can I use discriminators for interfaces?

我正在查看鉴别器字段,但我似乎只能对抽象类执行此操作。是这种情况吗?任何指针表示赞赏。我可以为接口使用鉴别器吗?

采纳答案by Vincent Ramdhanie

I think that it is possible to to make an interface the supertype of a mapping. You may not be able to use annotations though. Annotations play well with xml config files so you might have to add a hibernate config file to your project with the mappings that you need. But you will be able to keep the annotations for the rest of your project.

我认为可以使接口成为映射的超类型。但是,您可能无法使用注释。注释与 xml 配置文件配合得很好,因此您可能需要使用您需要的映射将休眠配置文件添加到您的项目中。但是您将能够保留项目其余部分的注释。

Thisissue discusses it more. It seems to end with a suggestion as to how to do it with annotations so who knows. I would suggest that xml is still safer for now This pageof the docs explains the xml mapping needed.

这个问题的详细讨论它。它似乎以关于如何使用注释来做这件事的建议结束,所以谁知道呢。我建议现在 xml 仍然更安全文档的这个页面解释了所需的 xml 映射。

回答by Andrea Francia

You can also introduce an abstract class without removing the interface.

您还可以在不移除接口的情况下引入抽象类。

// not an entity
public interface Account {
    public void doStuff();
}

@Entity
public abstract class BaseAccount {
    public void doStuff();
}


@Entity
public class OverSeasAccount extends AbstractAccount {
    public void doStuff() { ... }
}

@Entity
public class OverDrawnAccount extends AbstractAccount {
    public void doStuff() { ... }
}