我想在实体之间建立多对多关系,并且现在在MySql端为其使用联结表。现在,我需要一个类似于索引的JPA解决方案,该解决方案使我可以将这两个表/实体的ID用作键/索引,而无需实体本身,以避免某些交叉包引用。查询时,我具有EntityA的ID,并希望找到它的EntityB的ID,仅此而已。我认为这可能会起作用:
(这不是因为我没有JunctionEntity的ID,而且如果我使用ID,那么当唯一的唯一事物应该是两个条目都在一起时,显然条目必须是唯一的。PK类也不起作用,因为它会仍要求对两个实体都说引用)
实体A:
@Entity
@Table(name = "EntityA")
})
public class EntityA {
@Id
private int id;
}
实体B:
@Entity
@Table(name = "EntityB")
})
public class EntityB {
@Id
private int id;
}
JunctionEntity:
@Entity
@Table(name = "junction", indexes = {
@Index(name = "ix_a_b", columnList = "a_id, b_id")
})
public class JunctionEntity {
private int a_id;
private int b_id;
}
MySQL for JunctionTable:
CREATE TABLE junction (
a_id INT NOT NULL,
b_id INT NOT NULL,
CONSTRAINT junction_fk_a FOREIGN KEY (a_id) REFERENCES entityA (id),
CONSTRAINT junction_fk_b FOREIGN KEY (b_id) REFERENCES entityB (id)
);
CREATE UNIQUE INDEX ix_a_b
ON junction (a_id, b_id);
最佳答案
您可以添加主键,并使用a_id,b_id或同时使用两者在联结表中进行搜索。
CREATE TABLE junction (
id INT NOT NULL,
a_id INT NOT NULL,
b_id INT NOT NULL,
CONSTRAINT junction_fk_a FOREIGN KEY (a_id) REFERENCES entityA (id),
CONSTRAINT junction_fk_b FOREIGN KEY (b_id) REFERENCES entityB (id)
);
您不需要知道联结表的ID。您可以这样查询联结:
select b_id from junction where a_id = ?;