How to mix inheritance strategies with JPA annotations and Hibernate?

后端 未结 2 1593
春和景丽
春和景丽 2020-11-27 04:36

According to the Hibernate Reference Documentation it should be possible to mix different inheritance mapping strategies when using Hibernate\'s XML-Metadata:
h

2条回答
  •  情深已故
    2020-11-27 05:25

    Just for the sake of clarity, here is Pascal's solution applied to the example code from my question:

    @Entity
    @Inheritance( strategy = InheritanceType.SINGLE_TABLE )
    @DiscriminatorColumn( name = "entityType", 
            discriminatorType = DiscriminatorType.STRING )
    public abstract class A implements Serializable
    {
        @Id
        private String id;
    
        // other mapped properties...
    }
    
    @Entity
    @SecondaryTable( name = "BB" )
    public class BB extends A
    {
        @Basic( optional = false)
        @Column( table = "BB" )
        private String property1;
    
        // other mapped properties and associations...
    }
    
    @Entity
    public class BB1 extends BB
    {
        // other stuff, not necessarily mapped...
    }
    
    @Entity
    public class BB2 extends BB
    {
        // other stuff, not necessarily mapped...
    }
    
    @Entity
    @SecondaryTable( name = "CC" )
    public class CC extends A
    {
        @ManyToOne( optional = false)
        @JoinColumn( table = "CC" )
        private SomeEntity association1;
    
        // other mapped properties and associations...
    }
    
    @Entity
    public class CC1 extends CC
    {
        // other stuff, not necessarily mapped...
    }
    
    ...
    

    I've successfully applied this approach to my problem, and I'll stick to it for the time being. However I still see the following disadvantages:

    • The discriminator column is located in the main table for the hierarchy, the table for root-enity A. In my case, it would be sufficient to have the discriminator column in the secondary tables BB and CC.

    • Anytime one adds properties and associations to subclasses of BB or CC, he/she has to specify that they should be mapped to the respective secondary table. Would be nice, if there was a way to make that the default.

提交回复
热议问题