Spring Data JDBC反转一对多导航 [英] Spring Data JDBC invert OneToMany navigation

查看:231
本文介绍了Spring Data JDBC反转一对多导航的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个不愿更改的现有数据方案.有两个实体/表:parentchild,其子项具有外键列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不直接支持从ChildParent的引用.如果将ParentChild建模为一个聚合,即具有直接引用,则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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆