I have 3 tables in a postgres data base and am using R2dbc to query and connect them in a relational manner.
I have 3 entity classes (possibly shouldn't be data classes, but shouldn't effect the example)
@Entity
@Table(name = "parent", schema = "public", catalog = "Test")
data class MyParentObject(
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Id
@org.springframework.data.annotation.Id
@Column(name = "id")
var id: Int = 0,
@Transient
var childData: List<MyChildObject>? = null
)
@Entity
@Table(name = "child", schema = "public", catalog = "Test")
data class MyChildObject(
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Id
@org.springframework.data.annotation.Id
@Column(name = "id")
var id: Int = 0,
@Column(name = "parent_id")
var parentId: Int? = null
@Transient
var grandchildData: List<MyGrandchildObject>? = null
)
@Entity
@Table(name = "grandchild", schema = "public", catalog = "Test")
data class MyGrandchildObject(
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Id
@org.springframework.data.annotation.Id
@Column(name = "id")
var id: Int = 0
@Column(name = "child_id")
var childId: Int? = null
)
parent is one-to-many to child which is one-to-many of grandchild. parent_id and child_id act like fkeys.
I have a RestController which can return all Parent data populated with all child Data through these methods
fun viewAllParents(): Mono<MutableList<MyParentObject>> =
parentRepository.findAll()
.flatMap { Mono.just(it).addChildData(it.id) }
.collectList()
fun Mono<MyParentObject>.addChildData(id: Int): Mono<MyParentObject> =
this.zipWith(childRepository.getAllByParentIdEquals(id).collectList())
.map {
it.t1.childData = it.t2
it.t1
}
And I have another RestController that can return all ChildData with all Grandchild data (much the same as above) through these methods
fun viewAllChildren(): Mono<MutableList<MyChildObject>> =
childRepository.findAll()
.flatMap { Mono.just(it).addGrandchildData(it.id) }
.collectList()
fun Mono<MyChildObject>.addGrandchildData(id: Int): Mono<MyChildObject> =
this.zipWith(childOfChildRepository.getAllByChildIdEquals(id).collectList())
.map {
it.t1.childOfChildData = it.t2
it.t1
}
What I can't do and is my question, is how do I get viewAllParents()
to also populate with Grandchild data. Do I need to convert var grandchildData: List<MyGrandchildObject>
to a Flux and zip it with a new flux from the grandchildRepository? Or Am I looking at this the wrong way?
Any pointers would be much appreciated.