Mapping multi-Level inheritance in Hibernate with Annotations

前端 未结 3 1636
广开言路
广开言路 2020-12-15 13:40

Take the situation listed in this question:

Mapping multi-Level inheritance in Hibernate

How would this mapping be done with Annotations rather than an hbm f

相关标签:
3条回答
  • 2020-12-15 14:14

    What specifically are you having trouble with? Mapping class hierarchy via joined subclasses is pretty straightforward:

    @Entity
    @Inheritance(strategy=InheritanceType.JOINED)
    public class A implements Serializable { ... }
    
    @Entity
    public class B extends A { ... }
    
    @Entity
    @PrimaryKeyJoinColumn(name="A_ID")
    public class C extends A { ... }
    
    @Entity
    @PrimaryKeyJoinColumn(name="B_ID")
    public class D extends B { ... }
    

    Update (based on Michal's comment).

    In case you do want to use discriminators (and you should have a good reason to do so), it's possible to do so by mixing table-per-class-hierarchy strategy with secondary tables:

    @Entity
    @Table(name="A_table")
    @Inheritance(strategy=InheritanceType.SINGLE_TABLE)
    @DiscriminatorColumn(name="entity_type")
    @DiscriminatorValue("A")
    public class A implements Serializable { ... }
    
    @Entity
    @SecondaryTable(name="B_table")
    public class B extends A { ... }
    
    @Entity
    @SecondaryTable(name="C_table", pkJoinColumns={
        @PrimaryKeyJoinColumn(name="A_ID", referencedColumnName="ID")
    ))
    public class C extends A { ... }
    
    @Entity
    @SecondaryTable(name="D_table", pkJoinColumns={
        @PrimaryKeyJoinColumn(name="B_ID", referencedColumnName="ID")
    ))
    public class D extends B { ... }
    

    The downside to this approach is you'll have to explicitly specify the table for each property mapped:

    public class D extends B {
      @Column(table="D_table")
      private String someProperty;
    
      ...
    }
    
    0 讨论(0)
  • 2020-12-15 14:14

    Inheritance between @Entity annotated classes is picked up automatically. So if you class A is annotated and class B is also annotated with @Entity and extends A, and C extends B and is also @Entity annotated all will be picked up.

    I have not used joined subclasses combined with discriminator values, but I'm sure it will be very similar to what is done in XML (using @DiscriminatorColumn and @DiscriminatorValue)

    0 讨论(0)
  • 2020-12-15 14:17

    This is the exact thing which worked fine for me:

    @Entity
    @Inheritance(strategy = InheritanceType.JOINED)
    @DiscriminatorColumn(name="LoanType",discriminatorType="String")
    @Table(name = "A")
    public class A implements Serializable{
    }
    
    @Entity
    @Table(name= "B")
    @PrimaryKeyJoinColumn(name = "B_ID", referencedColumnName ="A_ID")
    public class B extends A{
    }
    
    
    @Entity
    @Table(name= "C")
    @PrimaryKeyJoinColumn(name = "C_ID", referencedColumnName = "B_ID")
    public class C extends B{}
    
    0 讨论(0)
提交回复
热议问题