persitsing an interface type with JPA

Consider this scenario. You have several classes implementing the same interface and you’d like to persist this interface type within an entity. The JPA is not able to handle that, but there is a workaround!

Lets make an example: A Plate (entity) has the attribute of type Fruit (interface). The apple, orange and the banana implement Fruit.

Now it would be great, if we could simply call plate.setFruit(apple) for example. The problem is, that JPA cannot handle multitype attributes (yet) . Use the following workareoud to make this functionality working:

The entities used for the exampe are:

Now the trick is to create a class with references to all of the Fruit interface implementing classes, which is later embedded in the Plate class:

This class is then embedded in the Plate entity:

Please consider this mapping possibility as bad practice, slow and hard/expensive to query!

Leave a Reply

Your email address will not be published. Required fields are marked *