Reputation: 95
I have to make the domain-layer of a collage project. We have few standards, like we have to use Hibernate and the database also is fix.
The relevant part of the database looks nearly like that:
BusEntitys (Table 1)
BusType (Table 2)
The problem I have is that there are 2 types of buses in the domain-layer distinguish by the discriminator in the BusType-table:
@Entity
class Bus
{
@Id
int _id;
...
}
@Entity
class BusSubClass1 extends Bus
{
...
}
@Entity
class BusSubClass2 extends Bus
{
...
}
Is there a way to map something like this with Hibernate and JPA? Thanks for every answer.
Jochen Morent
Upvotes: 1
Views: 1696
Reputation: 8219
Yes, there are few ways to map such scenario. JPA provides support for three different data representations:
In other words depending on inheritance type used you will get different database model. Various JPA providers may support additional inheritance strategies.
Consider the following example:
@Entity
@Inheritance //by default SINGLE_TABLE strategy
@DiscriminatorColumn( //not supported for TABLE_PER_CLASS strategy
name = "BUS_TYPE",
discriminatorType = DiscriminatorType.INTEGER
)
public abstract class Bus {
@Id
protected int id;
protected int seats;
public Bus() {
}
}
@Entity
@DiscriminatorValue(value = "1") //not supported for TABLE_PER_CLASS strategy
public class BusSubClass1 extends Bus {
private String specific1;
public BusSubClass1() {
}
}
@Entity
@DiscriminatorValue(value = "2") //not supported for TABLE_PER_CLASS strategy
public class BusSubClass2 extends Bus {
@Temporal
private Data specific2;
public BusSubClass2() {
}
}
Using InheritanceType.SINGLE_TABLE
strategy leads to a single database table containing all concrete entity types:
Bus
ID BUS_TYPE SEATS SPECIFIC1 SPECIFIC2
-- -------- ----- --------- ---------
1 1 50 qwerty
2 1 55 asdfgh
3 2 30 2014-01-01
Using InheritanceType.JOINED
strategy leads to multiple database tables per entity type (all shared fields from Bus
are stored in the corresponding table):
Bus BusSubClass1 BusSubClass2
ID BUS_TYPE SEATS ID SPECIFIC1 ID SPECIFIC2
-- -------- ----- -- --------- -- ---------
1 1 50 1 qwerty 3 2014-01-01
2 1 55 2 asdfgh
3 2 30
Using InheritanceType.TABLE_PER_CLASS
strategy leads to exqactly one database table per entity type (all shared fields from Bus
are redefined in the concrete subclasses):
BusSubClass1 BusSubClass2
ID SEATS SPECIFIC1 ID SEATS SPECIFIC2
-- ----- --------- -- ----- ---------
1 50 qwerty 3 30 2014-01-01
2 55 asdfgh
Upvotes: 3