JPA entity with a interface attribute, is it possible?

自闭症网瘾萝莉.ら 提交于 2020-01-01 04:08:06

问题


I have the following entity:

@Entity
public class TestCaseStep implements JPAEntity<Integer> {

        ...

    @Column(name="STEP_NUMBER")
    private Integer stepNumber;

    @Enumerated(EnumType.STRING)
    @Column(name="ACTION")
    private Action action;

    **@ManyToOne
    @JoinColumn(name="connector")
    private ScriptItem connector;**

My attribute ScriptItem is a interface for 3 other classes. Is it possible to configure JPA to set the correct class id in runtime execution?

Other resources:

public interface ScriptItem {

    String getValue();
    ScriptItemType getType();
}

@Entity
@Table(name="DAT_FEED_XML")
public class FeedXml implements JPAEntity<Integer>, ScriptItem {
    ...
}

@Entity
@Table(name="DAT_DB_STMT")
public class DbStatement implements JPAEntity<Integer>, ScriptItem {
       ...
}

Which annotations should I use to let JPA understand that I want to save the id of one of the 3 classes?

Thanks in advance,


回答1:


It is really a good idea but unfortunately directly mapping interfaces as an entity attribute is not supported by JPA.

You can only map top level classes directly annotated with @Entity. This top level class may implement an interface though.

This feature has been requested and discussed for a long time.

Also take a look at this and this.

Depending on what you're trying to accomplish, @Inheritance annotation with table-per-class strategy could be an option.

I hope it helps.




回答2:


No, not possible with JPA or Hibernate.

It does seem strange, when coding in the Java language which allows for attributes to be interfaces, that a persistence standard like JPA, intended for Java, does not support persisting attributes that are interfaces.

I always found it really very frustrating when my ORM would force me to refactor my 'pure' OO model just so that it could persist it.

It's not that it's technically impossible to implement persisting of interface attributes - in fact JDO has supported persistence of interfaces since forever which is why I started using it years ago for all of my own projects.

I've been tempted to switch to JPA, not because it is technically superior (in fact, quite the opposite) but just because of "herd mentality".

In recent contract work I have been forced to gain experience with JPA/Hibernate and in doing so, have lived out the many limitations and inefficiencies of that combination compared with JDO/DataNucleus. This was a great experience because it helped me quell my desire to join "the herd" :)




回答3:


You need to setup your inheritance of ScriptItem correctly in JPA using whatever strategy you prefer (see the docs) and then JPA will be smart about it.



来源:https://stackoverflow.com/questions/12627607/jpa-entity-with-a-interface-attribute-is-it-possible

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