[英]Spring boot data jdbc implement Many to Many relationship with same entity
我如何 model 与具有 spring 数据 jdbc 的同一实体的多对多关系。 我有一个任务可以依赖于其他几个任务的场景,同时该任务有依赖项,但它是相同的 object。 我以前用 jpa 做过这个
@JoinTable(
name = "task_dependencies",
joinColumns = @JoinColumn(name = "dependent_process"),
inverseJoinColumns = @JoinColumn(name = "depends_on_process")
)
private final Set<AsyncTask> dependencies = new HashSet<>();
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "dependencies")
private final Set<AsyncTask> dependents = new HashSet<>();
在您的示例中, AsyncTask
是一个聚合和它自己的聚合根。 因此,从一个AsyncTask
到另一个的引用被视为聚合之间的引用。
在 Spring 数据 JDBC(在域驱动设计中也建议)对其他聚合的引用将被实现为 id,而不是实际的 ZD52387880E1EA22817A72D3759213819 引用。
对于映射表,您需要一个单独的小实体,它成为关系一侧聚合的一部分。
您可以使用AggregateReference
而不仅仅是一个Id
,以避免到处都有Long
值。
完整的 model 可能如下所示:
@Table
class AsyncTask {
@Id
Long id;
String name;
@MappedCollection(idColumn = "FROM_ID")
Set<DependentTask> dependents = new HashSet<>();
AsyncTask(String name) {
this.name = name;
}
public void addDependent(AsyncTask task) {
dependents.add(new DependentTask(task.id));
}
}
@Table
class DependentTask {
@Column("TO_ID")
AggregateReference<AsyncTask, Long> id; // this is the Id of the dependent task, note that it is not marked with `@Id`
DependentTask(Long id) {
this.id = AggregateReference.to(id);
}
}
并像这样使用:
AsyncTask one = repo.save(new AsyncTask("one"));
AsyncTask two = repo.save(new AsyncTask("two"));
AsyncTask three = new AsyncTask("three");
three.addDependent(one);
three.addDependent(two);
repo.save(three);
one.addDependent(two);
repo.save(one);
two.addDependent(two);
repo.save(two);
底层数据库架构如下所示:
CREATE TABLE ASYNC_TASK (
ID INTEGER IDENTITY PRIMARY KEY,
NAME VARCHAR (200) NOT NULL
);
CREATE TABLE DEPENDENT_TASK (
FROM_ID INTEGER NOT NULL REFERENCES ASYNC_TASK(ID),
TO_ID INTEGER NOT NULL REFERENCES ASYNC_TASK(ID)
);
For more information on the topic read Spring Data JDBC, References, and Aggregates and Spring Data JDBC - How do I make Bidirectional Relationships?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.