Inherited abstract class with JPA (+Hibernate)

前端 未结 3 798
忘掉有多难
忘掉有多难 2020-12-03 02:11

How would you configure annotations in the following example code? I\'d like to stick with JPA annotations only and avoid Hibernate specific dependencies. Is the cod

相关标签:
3条回答
  • 2020-12-03 02:48

    From JPA 1.0 specification:

    Both abstract and concrete classes can be entities. Both abstract and concrete classes can be annotated with the Entity annotation, mapped as entities, and queried for as entities.

    Entities can extend non-entity classes and non-entity classes can extend entity classes.

    As you want a single table, you should use Single Table inheritance.

    Just define a discriminator column as follows:

    @Entity
    @DiscriminatorColumn(name="REF_TYPE")
    public abstract class RefData {
    

    But if you do not want to rely on JPA inheritance strategies, you can use MappedSuperclass instead:

    @MappedSuperclass
    public abstract class RefData {
    

    JPA specification

    An entity may inherit from a superclass that provides persistent entity state and mapping information, but which is not itself an entity. Typically, the purpose of such a mapped superclass is to define state and mapping information that is common to multiple entity classes.

    Keep in mind you can not use @Entity and @MappedSuperclass at the same time.

    0 讨论(0)
  • 2020-12-03 02:49

    You can use one of the inheritance strategy to to this. Your case looks to be the case of Single class for the hierarchy.

    Check this

    0 讨论(0)
  • 2020-12-03 02:58

    @MappedSuperclass is worked for me. I was struggling to map a view to 2 objects which are Parent and child classes. My view is joined from 2 tables. Primary keys from both the tables are present in the view. @DiscriminatorColumn is not worked for me since it requires a column exclusively allotted to data type of the object and also it is throwing 'repeated Column in object exception' which I could not solve.

    I read this forum and I tried @MappedSuperclass annotation. It does the trick.

    I've put @MappedSuperclass at the superclass and put the @Id and @GeneratedValue in the superclass identifier. In the sublass I've given as

    @Entity
    @Table(name="view_name")
    

    and used sub class object to fetch the data from view. That's it.

    Inheritance in hibernate annotations for Joined table with out using @DiscriminatorColumn worked for me.

    0 讨论(0)
提交回复
热议问题