我有三个实体:A
、B
和C
,它们之间的关系如下:
class A{
@ManyToMany
List<B> bs;
//other attributes and getter setters
}
class B{
@ManyToMany
List<C> cs;
//other attributes and getter setters
}
class C{
//other attributes and getter setters
}
但是从我当前的实体类中,我可以使用 @JoinTable
在任意 2 个表之间建立关系。但我想要的是将所有 3 个实体之间的关系保存在一个单独的表中,将这些实体的主键作为列。 (外键)
如果我们假设实体 B
和 C
已经保存(插入)到数据库中,我将插入新的 A
实体,如下所示:
A:{
"A_id": 1
B:[
"B_id": 1
{
C:[
{"C_id": 1}, {"C_id": 2}
]
},
{
"B_id": 2
C:[
{"C_id": 2}
]
}
]
}
然后 A
应该保存在它的表中,并且关系应该在单独的表中列出,如下所示:
A_id B_id C_id
=====================
1 1 1
1 1 2
1 2 2
我看到的一个相关问题here .但我认为我的场景有所不同,因为我在所有实体 A
、B
和 C
之间建立了多对多关系。
我不是要完整的代码。只要解决了目的,任何方法或确切的引用都可以。谢谢
编辑:
我已尝试实现答案中提到的单独的关系表。但这种方法的问题是,当我从关系表中删除一行时,它还会从 B
和 C
的连接表中删除条目。 (影响实体B
和C
之前的关系)
此外,在更新更新行时,它更改(执行插入)到实体 B
和 C
的连接表中。这不是预期的行为。我希望此表仅用于存储实体之间的关系,而不是用于更改这些实体之间的先前关系。
以下是我的新关系表:
@Entity
@Table(name = "relation_table")
public class RelationEntity {
@Id
@Column(name = "pk_relation_id")
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Integer relatoinId;
@OneToOne
@JoinColumn(name = "a_id")
private A a;
@OneToOne
@JoinColumn(name = "b_id")
private B b;
@OneToOne
@JoinColumn(name = "c_id")
private C c;
//getter and setters
}
最佳答案
如果你想将关系
保存在单独的表中,那么你可以简单地做这样的事情来保存主键
@Entity
@Table(name = "relation_bridge")
public class RelationBridge {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne
@JoinColumn(name = "a")
private A a;
@ManyToOne
@JoinColumn(name = "b")
private B b;
@ManyToOne
@JoinColumn(name = "c")
private C c;
//getters & setters
}
编辑
When I remove a row from the relation table, It also removes the entry >from the join table of
B
andC
. (Affects the previous relation of >entitiesB
andC
)
除非明确定义,否则上述解决方案不应删除
parent
表中的条目。但是,您可能在其他类中使用其他映射,因此可以通过应用 Cascading 来控制此行为。在你的映射中。
关于java - 在 Spring Data JPA 中使用注释连接两个以上的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49941850/