Vamsee Krishna
Vamsee Krishna

Reputation: 145

Using Hibernate in case of a common table which holds metadata for several tables

I have the below scenario :

There is one table which maintains the metadata related to several entities. Below is the schema and how the table would look like :

Sample Table

Both TABLE_A and TABLE_B are mapped as Hibernate Entities and are backed by ClassA and ClassB. Now, how can I map this table in Hibernate such that I can achieve the below scenario :

ClassA classA = aService.getById("1234");

ClassB classB = bService.getById("1234");

classA.getAttributeValue(); -- Should return 12ab

classB.getAttributeValue(); -- Should return cs12

Is there a way where Hibernate can intelligently get the AttributeValue based on the type of the object from which the method is called?

Upvotes: 0

Views: 365

Answers (1)

mabi
mabi

Reputation: 5306

I think you're looking for Single table inheritance. So your classes could look like this:

@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
    name="entityType",
    discriminatorType=DiscriminatorType.STRING
)
@DiscriminatorValue("TABLE_A")
public class ClassA {
     @Id
     private String id;

     @Column(name = "ATTRIBUTE_NAME")
     private String name;

     @Column(name = "ATTRIBUTE_VALUE")
     private String value;
}

@Entity
@DiscriminatorValue("TABLE_B")
public class ClassB extends ClassA { ... } 

An alternative would be creating a common ancestor class and have Table_A mapped to it's own subclass entity.

Upvotes: 1

Related Questions