سؤال

Lets say I have an object model similar to the following:

abstract class Vehicle {
   String guid;
   String name;
   Double price;
}
class SUV extends Vehicle {
   Integer towingCapacity;
}
class Hybrid extends Vehicle {
   Integer batterySize;
}

I need to use JPA and map this hierarchy into the database. I've chosen to go with the 'Joined Table Per Class' approach, as outlined here: http://java.dzone.com/articles/jpa-implementation-patterns-mapping

So essentially I have a Vehicle parent table, with an SUV and Hybrid table having a foreign key to Vehicle. The reason I chose this solution is that I like the normalized schema, and in addition Vehicle.guid needs to be globally unique, so having a parent table with that field - as opposed to scattered throughout individual tables - simplifies this UNIQUE constraint.

I'm still relatively new to JPA and I have no idea how to set these up as JPA entities. Would class Vehicle be a MappedSuperclass? Also, I know I will need to add an @Id to each entity, but would SUV and Hybrid use the foreign key to the Vehicle table or would I have to use the primary key from the child tables as the identifier?

Thanks in advance.

هل كانت مفيدة؟

المحلول

The id is defined once for the whole hierarchy and is inherited, so the @Id attribute in the Vehicle class is enough.

@MappedSuperclass means that the class is not mapped to a separate table, but rather is part of it's children's tables. If you want a normalized schema, make Vehicle an entity as well.

You do not need to define foreign keys for child entities. This is done by the persistence provider and can be transparent to the developer.

Please note that JOINED inheritance strategy is less performant than the default SINGLE_TABLE strategy. SINGLE_TABLE requires more space and does not really support non-nullable columns for derived entities.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top