Search code examples
javahibernateormhibernate-mapping

Reverse inheritance mapping in Hibernate


I have a three tables:

Domain

|Field   |Type         |
| id     | BIGINT      |
| domain | VARVHAR(45) |
| other  | ...         |

Url

|Field      |Type         |
| id        | BIGINT      |
| domain_id | BIGINT      |
| url       | VARCHAR(45) |
| other     | ...         |

Data

|Field      |Type                  |
| id        | BIGINT               |
| type      | ENUM('DOMAIN','URL') |
| entity_id | BIGINT               |
| data      | ...                  |

Under other fields, witch contains in Domain and Url tables I understand the some fields, whitch different between themselves by types.

Field entity_id in the Data table must contain the ID from the table Domain or Url depending on value of type fields in the Data table.

How I can create this xml mapping for Hibernate use?


Solution

  • for my opinion, you'd better use @Inheritence and map the Data table with the parent entity like below:

    @Entity
    @Table(name="MODEL")
    @Inheritance(strategy=InheritanceType.SINGLE_TABLE)
    @DiscriminatorColumn(name="entity_type",discriminatorType=DiscriminatorType.STRING)
    public abstract class Model{
    
    @Id
    private int id;
    //other common attributes
    //getters& setters
    }
    

    then your Domain and Url classes

    @Entity
    @DiscriminatorValue(value="domain")
    public class Domain extends Model{
    private String domain;
    //getters&setters
    }
    

    //

    @Entity
    @DiscriminatorValue(value="url")
    public class Url extends Model{
    @ManyToOne
    private Domain domain;
    
    private String url;
    //getters & setters
    }
    

    and this will create a table named MODEL which will have 2 types (Domain & Url) with an extra column (entity_type) which will take as a value "domain" or "url" depending on the record type.

    later in your Data Entity:

    @Entity
    public class Data{
    private int id;
    @ManyToOne
    private Model model;
    }
    

    Ps: you dont need to add type attribute in Data entity anymore while you have the discreminator column entity_type