[英]How to annotate Map<Entity, Entity> with JPA?
該應用程序的堆棧: Spring MVC
, Spring DataJPA
, Hibernate
。 存在三個實體: student
、 tutor
、 theme
。
主題:
@Entity
@Table(name = "themes")
public class Theme {
// fields omitted
}
學生:
@Entity
@Table(name = "students")
public class Student {
private Map<Theme, Tutor> tutors;
// other fields omitted
}
導師:
@Entity
@Table(name = "tutors")
public class Tutor {
private Map<Theme, Student> students;
// other fields omitted
}
為了保存student-tutor-theme
關系,我想使用這個表(PostgreSQL) :
CREATE TABLE themes_students_tutors
(
theme_id INTEGER NOT NULL,
student_id INTEGER NOT NULL,
tutor_id INTEGER NOT NULL,
FOREIGN KEY (theme_id) REFERENCES themes (id) ON DELETE CASCADE,
FOREIGN KEY (student_id) REFERENCES students (id) ON DELETE CASCADE,
FOREIGN KEY (tutor_id) REFERENCES tutors (id) ON DELETE CASCADE
)
我如何注釋實體中的tutors
和students
字段,因為他們的內容正確保留在此表中?
就像@kolossus 提到的:使用@MapKeyJoinColumn
¹ 注釋,使類(或 map 字段)看起來像這樣(你可以忽略AbstractPersistable
的擴展):
學生:
public class Student extends AbstractPersistable<Long> {
@ManyToMany
@JoinTable(name = "themes_students_tutors", joinColumns = {
@JoinColumn(name = "student_id", referencedColumnName = "id") }, inverseJoinColumns = {
@JoinColumn(name = "tutor_id", referencedColumnName = "id") })
@MapKeyJoinColumn(name = "theme_id")
private Map<Theme, Tutor> tutors;
}
導師:
public class Tutor extends AbstractPersistable<Long> {
@ManyToMany
@JoinTable(name = "themes_students_tutors", joinColumns = {
@JoinColumn(name = "tutor_id", referencedColumnName = "id") }, inverseJoinColumns = {
@JoinColumn(name = "student_id", referencedColumnName = "id") })
@MapKeyJoinColumn(name = "theme_id")
private Map<Theme, Student> students;
}
鑒於此,將創建如下內容:
Hibernate: create table students (id bigint not null, primary key (id))
Hibernate: create table themes (id bigint not null, primary key (id))
Hibernate: create table themes_students_tutors (tutor_id bigint not null, student_id bigint not null, theme_id bigint not null, primary key (student_id, theme_id))
Hibernate: create table tutors (id bigint not null, primary key (id))
Hibernate: alter table themes_students_tutors add constraint FKm5l4is34t5gs14p4skkv3aup7 foreign key (student_id) references students
Hibernate: alter table themes_students_tutors add constraint FK8o0mm5ywi0l4hdxi4lgw4dbnu foreign key (theme_id) references themes
Hibernate: alter table themes_students_tutors add constraint FKa0n6jvie0kmk0pmikcuvtepxh foreign key (tutor_id) references tutors
¹:有關其他示例,請參閱@MapKeyJoinColumn
的 Javadoc 文檔
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.