Satya
Satya

Reputation: 2124

How to map two classes to one DB table in Hibernate

I am in the process of learning Hinbernate, so a thought passed if I could map two classes to one DB table.

Ex :

Class Developer {
    String name;
}

Class Manager {
    String name;
}

Whereas both these classes are mapped to one table, lets say by name Employee with one column of String datatype.

Will Hibernate be able to create rows in table based on the class I am using for creating. Or do you think there should be a discriminator column to differentiate between classes?

NOTE : There are no inheritance relationships between the classes, they are separate.

Upvotes: 1

Views: 3615

Answers (2)

Johanna
Johanna

Reputation: 5303

When you use xml mapping files, you simply can create two mapping files Developer.hbm.xml and Manager.hbm.xml, which both refer to the same database table. That works.

The problem is, you must ensure a table row only is loaded as a Developer or a Manager, but not as both. If for example you load them with session.createQuery("from Developer") and session.createQuery("from Manager"), then you have the same row two times in the session cache. If you then first modify and update Developer, after that you modify and update the same row in Manager, then the modification in Developer is lost, and the session cache is inconsistent.

Thus, a discriminator row is not absolutely necessary but highly recommended.

Upvotes: 1

user219438
user219438

Reputation:

Well, think in terms of the database schema, not your object model. How could anyone (no matter whether it is you or Hibernate), given a single record from your table, tell which entity it actually is?

You will either need to introduce some class hierarchy and use SINGLE_TABLE inheritance by adding a discriminator column to specify the type or map those entities into different tables.

Upvotes: 0

Related Questions