Skip to content

Instantly share code, notes, and snippets.

@dungdm93
Last active September 20, 2021 14:43
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dungdm93/62c36ca0bfab7749cbad to your computer and use it in GitHub Desktop.
Save dungdm93/62c36ca0bfab7749cbad to your computer and use it in GitHub Desktop.
[Java] [JPA] @mapkey example
import javax.persistence.*;
@Entity
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int courseCode;
public String name;
...
}
import javax.persistence.*;
@Entity
public class Semester {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int id;
public int year;
public int ordinal;
...
}
import javax.persistence.*;
import java.util.Map;
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int studentId;
public String firstName;
public String lastName;
// (Required either @OneToMany --or--- @ManyToMany)
@ManyToMany(cascade = CascadeType.ALL) // if the map value is NOT a basic type.
@JoinTable(name = "ENROLLMENTS",
joinColumns = @JoinColumn(name = "STUDENT"),
inverseJoinColumns = @JoinColumn(name = "SEMESTER"))
@MapKeyJoinColumn(name = "COURSE")
public Map<Course, Semester> enrollment;
...
}
@dungdm93
Copy link
Author

key\value @CollectionTable uni-directional @OneToMany bi-directional @OneToMany @ManyToMany
@MapKeyColumn link link link link
@MapKeyTemporal link link link link
@MapKeyEnumerated link link link link
@MapKeyJoinColumn link link link link

  • If the map key is NON-basic entity, the map key MUST be persisted (saved) before persist the holder.
  • If the relationship is many-to-many and the map value is NON-basic entity, the map value also MUST be persisted before persist the holder.

  • @ElementCollection is required if the map value is a basic type.
    Corresponding config annotation are @CollectionTable and @Column.
  • if the map value is NON-basic type, it's required either @OneToMany or @ManyToMany.
    Corresponding config annotation is @JoinTable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment