Can I make the typesafe heterogeneous container like the one fromf Bloch's Effective Java work with JPA?

186 Views Asked by At

What I need is something like

 public class Catalog {

     private Map<Class<?>, Object> options = new HashMap<Class<?>, Object>();

     public void addOption(Class><T>, T Option) {
            ...
     }

     public <T> T getSelectedOption() {
            ...
     }

 }

Which is a generic Catalog of Options that should represent a set of alternatives to choose from. Those could be TravelDestination, HotelCategory, CarBrand, etc.

How do I go about saving this construct into may database while preserving the typeinformation needed for reconstruction the internal map during runtime using JPA/Hibernate?

As an additional boundary condition:

Since Catalog should be modelled after its real-life counterpart I'd like to avoid an abstract Catalog and therefore introducing a new subclass for every alternative like TravelDestinationCatalog or HotelRoomCatalog, making Catalog defacto homogeneous.

1

There are 1 best solutions below

0
On BEST ANSWER

Why would you want one Map with Objects, identified by their class? At most you can put one Object per class in your Catalog. Why not add a ManyToOne relationship per alternative to your Catalog. This way you can still preserve lazy associations if needed, it's much more flexible and easier to do.