2020-04-04

Hibernate JPA @MapKeyClass Example

@MapKeyClass

The @MapKeyClass annotation is used to specify the type of the map key of a java.util.Map associations.

MapKeyClass Specifies the type of the map key for associations of type java.util.Map. The map key can be a basic type, an embeddable class, or an entity. If the map is specified using Java generics, the MapKeyClass annotation and associated type need not be specified; otherwise they must be specified.
The MapKeyClass annotation is used in conjunction with ElementCollection or one of the collection-valued relationship annotations (OneToMany or ManyToMany). The MapKey annotation is not used when MapKeyClass is specified and vice versa.


    Example 1:

    @Entity
    public class Item {
       @Id int id;
       ...
       @ElementCollection(targetClass=String.class)
       @MapKeyClass(String.class)
       Map images;  // map from image name to image filename
       ...
    }

    Example 2:

    // MapKeyClass and target type of relationship can be defaulted

    @Entity
    public class Item {
       @Id int id;
       ...
       @ElementCollection
       Map<String, String> images;
        ...
     }

     Example 3:

     @Entity
     public class Company {
        @Id int id;
        ...
        @OneToMany(targetEntity=com.example.VicePresident.class)
        @MapKeyClass(com.example.Division.class)
        Map organization;
     }

     Example 4:

     // MapKeyClass and target type of relationship are defaulted

     @Entity
     public class Company {
        @Id int id;
        ...
        @OneToMany
        Map<Division, VicePresident> organization;
     }

@MapKeyClass mapping example

@Entity
@Table(name = "person")
public static class Person {

@Id
private Long id;

@ElementCollection
@CollectionTable(
name = "call_register",
joinColumns = @JoinColumn(name = "person_id")
)
@MapKeyColumn( name = "call_timestamp_epoch" )
@MapKeyClass( MobilePhone.class )
@Column(name = "call_register")
private Map<PhoneNumber, Integer> callRegister = new HashMap<>();

//Getters and setters are omitted for brevity
}
create table person (
    id bigint not null,
    primary key (id)
)

create table call_register (
    person_id bigint not null,
    call_register integer,
    country_code varchar(255) not null,
    operator_code varchar(255) not null,
    subscriber_code varchar(255) not null,
    primary key (person_id, country_code, operator_code, subscriber_code)
)

alter table call_register
    add constraint FKqyj2at6ik010jqckeaw23jtv2
    foreign key (person_id)
    references person 

1 comment: