Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping multi-Level inheritance in Hibernate with Annotations

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?

like image 564
evan.leonard Avatar asked Dec 10 '09 20:12

evan.leonard


People also ask

What are the inheritance mapping strategies in Hibernate?

Hibernate supports the three basic inheritance mapping strategies: table per class hierarchy. table per subclass. table per concrete class.

Which of the following annotation is used for is a mapping?

JPA annotations are used in mapping java objects to the database tables, columns etc.

What are the types of inheritance mapping in GPA?

There are three inheritance mapping strategies defined in the hibernate: Table Per Hierarchy. Table Per Concrete class. Table Per Subclass.


1 Answers

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;

  ...
}
like image 143
ChssPly76 Avatar answered Oct 27 '22 11:10

ChssPly76