Meta
Meta

Reputation: 87

JPA - inheritance

Class Hierarchy:

| Vehicle
+ - Motorized
+ - - Truck

Database tables - putting the Vehicle fields in Motorized table but keeping Motorized and Truck as separate tables:

Motorized - has Vehicle fields
Truck - FK to Motorized

Is there a simple way to do this in JPA?

e.g. such that the following can be used:

EntityManager em = factory.createEntityManager();
Query q = em.createQuery("select t from Todo t");
List<Vehicle> vehicles = q.getResultList();

Can polymorphism be achieved with the find method?

Vehicle vehicle = em.find(Vehicle.class, 123);

Upvotes: 0

Views: 94

Answers (1)

Eric Galluzzo
Eric Galluzzo

Reputation: 3241

I think you're looking for JPA joined inheritance.

I'm not absolutely sure if you'll get polymorphism with the find method, but I would think so, since Hibernate maintains a first-level cache of all its objects, by ID; and if you requested that object by its ID, it would have to return an instance of the appropriate subclass.

Upvotes: 2

Related Questions