如何使用Reator和R2dbc压缩嵌套列表 [英] How to zip nested lists with reactor and R2dbc

查看:0
本文介绍了如何使用Reator和R2dbc压缩嵌套列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Postgres数据库中有3个表,正在使用R2dbc以关系方式查询和连接它们。

我有3个实体类(可能不应该是数据类,但不应该影响示例)

@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
)

父母是一对多对孩子,这是孙子对一对多。父项id和子项id的作用类似于fkey。

我有一个RestController,它可以通过这些方法返回填充了所有子数据的所有父数据

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
        }

我还有另一个RestController,它可以通过这些方法返回包含所有孙子数据的所有ChildData(与上面基本相同)

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
            }
我不能做的,也是我的问题是,我如何让viewAllParents()也填充孙子数据。我是否需要将var grandchildData: List<MyGrandchildObject>转换为Flux,并用孙子存储库中的新Flux将其压缩?还是我看错了?

如有任何提示,我们将不胜感激。

推荐答案

我真的很喜欢使用反应器获取分层数据的挑战。 我不知道Kotlin,但我曾尝试用Java重现这个问题。我无法创建具有父-子-孙层次结构的PostgreSQL表,但我尝试通过Web客户端模拟类似的东西(基本上逻辑将保持不变)。这是我的代码,这是我尝试执行的操作,并能够获得您想要的结果:https://github.com/harryalto/reactive-springwebflux

解决方案的关键在于处理程序代码,我使用该代码基于孩子列表构建一个子流,并使用该子流将所有子流联系在一起

public Flux<Parent> getFamiliesHierarchy() {

        return getAllParents()
            .flatMap(parent ->
                    getAllChildsList(parent.getId())
                            .flatMap(childList -> getChildsWithKids(childList))
                            .map(childList -> parent.toBuilder().children(childList).build()
                            )

            );
    }

下面是完整的代码

@Component
@Slf4j
public class FamilyHandler {

    @Autowired
    private WebClient webClient;

    public Flux<Parent> getAllParents() {
        return webClient
            .get()
            .uri("parents")
            .retrieve()
            .bodyToFlux(Parent.class);
    }

    public Mono<List<Child>> getAllChildsList(final Integer parentId) {
         ParameterizedTypeReference<List<Child>> childList = 
             new ParameterizedTypeReference<List<Child>>() {};
        return webClient
            .get()
            .uri("childs?parentId=" + parentId)
            .retrieve()
            .bodyToMono(childList);
    }

    public Flux<GrandChild> getGrandKids(final Integer childId) {
         return webClient
            .get()
            .uri("grandKids?childId=" + childId)
            .retrieve()
            .bodyToFlux(GrandChild.class);
    }

    public Mono<List<GrandChild>> getGrandKidsList(final Integer childId) {
         ParameterizedTypeReference<List<GrandChild>> grandKidsList = 
         new ParameterizedTypeReference<List<GrandChild>>() {};
         return webClient
            .get()
            .uri("grandKids?childId=" + childId)
            .retrieve()
            .bodyToMono(grandKidsList);
    }

    private Mono<List<Child>> getChildsWithKids(final List<Child> childList) {
        return Flux.fromIterable(childList).flatMap(child ->
                Mono.zip(Mono.just(child), getGrandKidsList(child.getId()))
                        .map(tuple2 ->        tuple2.getT1().toBuilder().grandChildren(tuple2.getT2()).build())
        ).collectList();
    }

    public Flux<Parent> getFamiliesHierarchy() {

        return getAllParents()
            .flatMap(parent ->
                    getAllChildsList(parent.getId())
                            .flatMap(childList -> getChildsWithKids(childList))
                            .map(childList -> parent.toBuilder().children(childList).build()
                            )

            );
    }

}`

我使用json-server模拟服务器

下面是我的db.json文件

  {
       "parents":[
      {
         "id": 1,
         "name" : "Parent1",
         "path":"1"
      },
      {
         "id": 2,
         "name" : "Parent2",
         "path":"2"
      }
     ],
     "childs":[
     {
         "id": 1,
         "parentId": 1,
         "name": "child1Parent1",
         "path":"1.1"
     },
     {
         "id":2,
         "parentId": 1,
         "projectName": "child2Parent1",
         "path":"1.2"

     },
     {
         "id":3,
         "parentId": 2,
         "projectName": "child1Parent2",
         "path":"2.1"

     },
     {
         "id":4,
         "parentId": 2,
         "projectName": "child2Parent2",
         "path":"2.2"

      }
   ],
   "grandKids":[
   {
     "id":1,
     "childId": 2,
     "projectName": "grandKid1child2Parent1",
     "path":"1.2.1"

   },
   {
     "id":3,
     "childId": 2,
     "projectName": "grandKid1child2Parent1",
     "path":"1.2.2"

  },
  {
     "id":2,
     "childId": 4,
     "projectName": "grandKid1child1Parent2",
     "path":"2.2.1"

  },
  {
     "id":4,
     "childId": 4,
     "projectName": "grandKid1child1Parent2",
     "path":"2.2.2"

  },
  {
     "id":5,
     "childId": 3,
     "projectName": "grandKid1child1Parent2",
     "path":"2.1.1"

  }
  
  ]
}

这是我的控制器代码

@RestController
@Slf4j
public class FamilyController {

    @Autowired
    private FamilyHandler familyHandler;

    @GetMapping(FAMILIES_ENDPOINT_V1)
    public Flux<Parent> viewAllParents() {
         return familyHandler.getFamiliesHierarchy();
    }

}

我们可以轻松地为r2DBC存储库更新代码。

--更新-- 我能够创建样例数据,并使用R2DBC创建了等效项 以下是指向gist

的链接

这篇关于如何使用Reator和R2dbc压缩嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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