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.
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).
I.e. I want something like this:
@Data
public class Parent {
@Id
private Long id;
}
@Data
public class Child {
@Id
private Long id;
private Parent parent;
}
Somewhat related question: Spring Data JDBC invert OneToOne navigation
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.
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.