Mapping multi-Level inheritance in Hibernate with Annotations

£可爱£侵袭症+ 提交于 2019-12-29 04:55:07

问题


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 file?


回答1:


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;

  ...
}



回答2:


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)




回答3:


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{}


来源:https://stackoverflow.com/questions/1883841/mapping-multi-level-inheritance-in-hibernate-with-annotations

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