Hibernate JPA @MapKeyJoinColumn Example

@MapKeyJoinColumn

The @MapKeyJoinColumn annotation is used to specify that the key of java.util.Map association is an entity association. The map key column is a FOREIGN KEY in a link table that also joins the Map owner’s table with the table where the Map value resides.

MapKeyJoinColumn Specifies a mapping to an entity that is a map key. The map key join column is in the collection table, join table, or table of the target entity that is used to represent the map. If no MapKeyJoinColumn annotation is specified, a single join column is assumed and the default values apply.

    Example 1:

    @Entity
    public class Company {
       @Id int id;
       ...
       @OneToMany   // unidirectional
       @JoinTable(name="COMPANY_ORGANIZATION",
                  joinColumns=@JoinColumn(name="COMPANY"),
                  inverseJoinColumns=@JoinColumn(name="VICEPRESIDENT"))
       @MapKeyJoinColumn(name="DIVISION")
       Map<Division, VicePresident> organization;
    }

    Example 2:

    @Entity
    public class VideoStore {
       @Id int id;
       String name;
       Address location;
       ...
       @ElementCollection
       @CollectionTable(name="INVENTORY",
                        joinColumns=@JoinColumn(name="STORE"))
       @Column(name="COPIES_IN_STOCK")
       @MapKeyJoinColumn(name="MOVIE", referencedColumnName="ID")
       Map<Movie, Integer> videoInventory;
       ...
     }

     @Entity
     public class Movie {
        @Id long id;
        String title;
        ...
     }

     Example 3:

     @Entity
     public class Student {
        @Id int studentId;
        ...
        @ManyToMany  // students and courses are also many-many
        @JoinTable(name="ENROLLMENTS",
                   joinColumns=@JoinColumn(name="STUDENT"),
                   inverseJoinColumns=@JoinColumn(name="SEMESTER"))
        @MapKeyJoinColumn(name="COURSE")
        Map<Course, Semester>  enrollment;
        ...
     }

Value type map with an entity as a map key

public enum PhoneType {
LAND_LINE,
MOBILE
}

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

@Id
private Long id;

@Temporal(TemporalType.TIMESTAMP)
@ElementCollection
@CollectionTable(name = "phone_register")
@Column(name = "since")
private Map<Phone, Date> phoneRegister = new HashMap<>();

//Getters and setters are omitted for brevity

}

@Embeddable
public static class Phone {

private PhoneType type;

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

//Getters and setters are omitted for brevity

}

Comments

Popular posts from this blog

Spring Elasticsearch Operations

Network Error and Timeout on Authorize.net JS

Object oriented programming concepts (OOPs)