JPA mapping interfaces

六月ゝ 毕业季﹏ 提交于 2019-12-21 02:53:12

问题


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.

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

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?


回答1:


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.

This issue 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 page of the docs explains the xml mapping needed.




回答2:


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() { ... }
}


来源:https://stackoverflow.com/questions/281503/jpa-mapping-interfaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!