Hibernate JPA @MapKeyEnumerated Example

@MapKeyEnumerated

The @MapKeyEnumerated annotation is used to specify that the key of java.util.Map association is a Java Enum.

MapKeyEnumerated Specifies the enum type for a map key whose basic type is an enumerated type. The MapKeyEnumerated annotation can be applied to an element collection or relationship of type java.util.Map, in conjunction with the ElementCollection, OneToMany, or ManyToMany annotation. If the enumerated type is not specified or the MapKeyEnumerated annotation is not used, the enumerated type is assumed to be ORDINAL.

Example:

   public enum ProjectStatus {COMPLETE, DELAYED, CANCELLED, IN_PROGRESS}

   public enum SalaryRate {JUNIOR, SENIOR, MANAGER, EXECUTIVE}

   @Entity public class Employee {
       @ManyToMany
       public Projects<ProjectStatus, Project> getProjects() {...}
     
       @OneToMany
       @MapKeyEnumerated(STRING)
       public Map<SalaryRate, Employee> getEmployees() {...}
       ...
   }


In the following example, you can see that @MapKeyEnumerated was used so that the Phone enumeration becomes the map key.

Bidirectional Map

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

@Id
private Long id;

@OneToMany(mappedBy = "person", cascade = CascadeType.ALL, orphanRemoval = true)
@MapKey(name = "type")
@MapKeyEnumerated
private Map<PhoneType, Phone> phoneRegister = new HashMap<>();

//Getters and setters are omitted for brevity

public void addPhone(Phone phone) {
phone.setPerson( this );
phoneRegister.put( phone.getType(), phone );
}
}

@Entity(name = "Phone")
public static class Phone {

@Id
@GeneratedValue
private Long id;

private PhoneType type;

@Column(name = "`number`")
private String number;

private Date since;

@ManyToOne
private Person person;

//Getters and setters are omitted for brevity

}
CREATE TABLE Person (
    id BIGINT NOT NULL ,
    PRIMARY KEY ( id )
)

CREATE TABLE Phone (
    id BIGINT NOT NULL ,
    number VARCHAR(255) ,
    since TIMESTAMP ,
    type INTEGER ,
    person_id BIGINT ,
    PRIMARY KEY ( id )
)

ALTER TABLE Phone
ADD CONSTRAINT FKmw13yfsjypiiq0i1osdkaeqpg
FOREIGN KEY (person_id) REFERENCES Person

Comments

Popular posts from this blog

Spring Elasticsearch Operations

Network Error and Timeout on Authorize.net JS

Object oriented programming concepts (OOPs)