Abbath
Abbath

Reputation: 1012

Hibernate create tables in db from inheritors

Hello Can you say how to create tables in DB from iheritors (not create one table for base class with inheritors with descriminators)? for example: I have base abstract class:

public abstract class Person
{
      public string Name;

}

and some inheritors like:

 public class Student : Person 

    public string University;

 }

 public class Driver : Person 
 {
    public string CarName;

 }

I need in DataBase Tables: Student: -id -Name -University

and Driver: -id -Name: -CarName

Upvotes: 1

Views: 54

Answers (1)

Thomas W
Thomas W

Reputation: 14164

You seem to be talking about "table per concrete subclass". This approach doesn't need a discriminator, but requires column-names be common between the separate tables (as internally, it fetchs via a UNION).

See: http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/inheritance.html#inheritance-tablepersubclass

I will note that your "Person, Driver, Student" example is likely an incorrect design -- as the same person can be both a Driver and a Student.

I assume you want to keep the STUDENT and DRIVER table design, which is simple, and that you don't really want a unified role-based system where Person -> Driver and Person -> Student are represented as relationships.

Following that assumption, you could either:

  1. Remove the common superclass Person from Hibernate mappings altogether -- since it won't really correct to retrieve "all People" by it, since people who are both Drivers and Students will be duplicated; and/or

  2. Replace the common superclass 'Person' with an interface 'IPersonInfo', not mapped by Hibernate; or,

  3. Weaken the definition of superclass 'Person' & rename it to 'PersonInfo', so it no longer implies identity (since each unique record is no longer guaranteed to be a single unique person).

If this isn't a toy design & you wanted to accurately model this or a more extensive system, you'd have to design the model properly:

4) Separate 'Person' entity from the Roles they can have. Student, Driver etc then descend from Role (probably an abstract class, so it can be mapped by Hibernate). Roles are then associated/related from Person, either by several 0..1 or as a big bag of Roles.

Upvotes: 2

Related Questions