Spring Data JDBC反转一对多导航 [英] Spring Data JDBC invert OneToMany navigation
问题描述
我有一个不愿更改的现有数据方案.有两个实体/表:parent
和child
,其子项具有外键列parent_id
.这是1个(父母)与n个(孩子)的关系.
I have an existing data scheme I'm reluctant to change. There are two entities/tables: parent
and child
, with child having the foreign key column parent_id
. It's a 1(parent)-to-n(children) relationship.
在Spring Data JDBC中是否可能具有Child
类引用Parent
而没有Parent
具有Set<Child>
属性?也许两者都有? (我知道可以使用hibernate,但是我想继续使用JDBC).
Is it possible within Spring Data JDBC to have Child
class reference Parent
and not Parent
have a Set<Child>
property? Maybe both? (I know it is possible with hibernate, but I'd like to stay with JDBC).
即我想要这样的东西:
@Data
public class Parent {
@Id
private Long id;
}
@Data
public class Child {
@Id
private Long id;
private Parent parent;
}
一些相关的问题: Spring Data JDBC反转OneToOne导航
推荐答案
Spring Data JDBC不直接支持从Child
到Parent
的引用.如果将Parent
和Child
建模为一个聚合,即具有直接引用,则Parent
必须是聚合根.因此,任何孩子始终只能通过Parent
访问.因此,反向引用应该是多余的.
Spring Data JDBC doesn't offer direct support for a reference from Child
to Parent
. If you are modelling Parent
and Child
as one aggregate, i.e. with a direct reference, Parent
must be the aggregate root. So any child gets only accessed the via the Parent
at all times. Therefore a back reference should be superfluous.
实际上,渴望有一个反向引用可能表明这两者并不是真正形成一个单一的集合,而是分开的集合,因此应该进行建模.参见 https://spring.io/blog /2018/09/24/spring-data-jdbc-references-and-aggregates
Actually, the desire to have a back reference might be an indication that the two don't really form a single aggregate but separate aggregates and should be modelled as such. See https://spring.io/blog/2018/09/24/spring-data-jdbc-references-and-aggregates
But if you really want your back reference you can easily establish that in an AfterLoadCallback
.
For this mark the back reference with the @Transient
annotation so it doesn't get actually stored in the database.
Then in the AfterLoadCallback
which will get triggered once for each Parent
navigate from the Parent
to each Child
and set the back reference.
这篇关于Spring Data JDBC反转一对多导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!