2.13.8.7. Map Mapping

All map fields in JPA are modeled on either one to many or many to many associations. The map key is always derived from an associated entity’s field. Thus map fields use the same mappings as any one to many or many to many fields, namely dedicated join tables or bidirectional relations. The only additions are the MapKey annotation and map-key element to declare the key field. We covered these additions in Map Key.

For a map of basic types the key is held in a column of its own. Unless MapKeyColumn names it, the column defaults to the name of the field or property + _KEY. To use the default of OpenJPA releases before 4.2.0, KEY (which most dictionaries turn into KEY0, as KEY is a reserved word), set the openjpa.Compatibility option UseSpecDefaultMapKeyColumnName to false.

jpa map

The example below maps Subscription's map of LineItems to the SUB_ITEMS join table. The key for each map entry is the LineItem's num field value.

Example 39. Join Table Map Mapping
package org.mag.subscribe;

@Entity
@Table(name="SUB", schema="CNTRCT")
public class Subscription {

    @OneToMany(cascade={CascadeType.PERSIST,CascadeType.REMOVE})
    @MapKey(name="num")
    @JoinTable(name="SUB_ITEMS", schema="CNTRCT",
        joinColumns=@JoinColumn(name="SUB_ID"),
        inverseJoinColumns=@JoinColumn(name="ITEM_ID"))
    private Map<Long,LineItem> items;

    ...

    @Entity
    @Table(name="LINE_ITEM", schema="CNTRCT")
    public static class LineItem
        extends Contract {

        private long num;

        ...
    }
}

The same metadata expressed in XML:

<entity class="org.mag.subscribe.Subscription">
    <table name="SUB" schema="CNTRCT"/>
    <attributes>
        ...
        <one-to-many name="items">
            <map-key name="num">
            <join-table name="SUB_ITEMS" schema="CNTRCT">
                <join-column name="SUB_ID"/>
                <inverse-join-column name="ITEM_ID"/>
            </join-table>
            <cascade>
                <cascade-persist/>
                <cascade-remove/>
            </cascade>
        </one-to-many>
        ...
    </attributes>
</entity>
<entity class="org.mag.subscribe.Subscription.LineItem">
    <table name="LINE_ITEM" schema="CNTRCT"/>
    <attributes>
        ...
        <basic name="num"/>
        ...
    </attributes>
</entity>