我想在实体之间建立多对多关系,并且我现在在 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;
}
连接实体:
@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 连接表:
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 = ?;
关于java - JPA 中的多对多关系与索引可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46026791/