Search code examples
javahibernatehbm

Mapping Map<Interface,Interface> with Hibernate


Hey people, i have a the following map* which is giving me lots of trouble:

Map<MetricSourceInterface, AliasesInterface>

MetricSourceInterface is an entity with simple properties. AliasesInterface is an entity with only an Id and a list of strings.

Hibernate is creating the database schema so theres no problem with changing it whatsoever.

On a side-note, this is a sub problem from trying to map:

Map<MetricSourceInterface, List<String>>

Does anyone know the proper way to solve this?

Theres only one limitation for this, i dont want to create an UserType for AliasesInterface or List

Thx in advance :)


*edited with pstanton's correction :)


Solution

  • As long as AliasesInterface is indeed an entity in Hibernate sense, there's really no problem with mapping this:

    @OneToMany(targetEntity=AliasInterface.class)
    @MapKeyManyToMany(targetEntity=MetricSourceInterface.class,  joinColumns=@JoinColumn(name="metric_source_id"))
    private Map<MetricSourceInterface, AliasesInterface> myMap;
    

    Note that the above assumes that both AliasInterface and MetricSourceInterface are entities; if they are indeed interfaces you'll need to refer to their concrete implementations instead.

    Keep in mind that @MapKeyManyToMany is Hibernate extesion to JPA. More details / examples on mapping collections are in Hibernate docs.

    Update: The same approach using XML mapping files:

    <map name="myMap">
      <key column="owner_id"/> <!-- FK to owner entity table -->
      <map-key-many-to-many column="metric_source_id" class="MetricSourceInterface"/>
      <one-to-many class="AliasesInterface"/>
    </map>
    

    There are more details here and other examples here.