多行插入行 PostgreSQL Java Spring Webflux

huangapple go评论72阅读模式
英文:

Multiple insert rows PostgreSQL Java Spring Webflux

问题

我是新手使用Spring WebFlux我正在尝试向数据库插入多行数据

我正在创建一个用于向数据库插入数据的REST API

我有一个用于保存Flux对象的服务

public Flux<FileUpload> create(FileUpload fileUpload) {
    Flux<FileUpload> attachments = Flux.just(fileUpload)
        .map(upload -> {
            new FileUpload(upload);
            this.fileUploadRepository.save(upload);

            return upload;
        });

    return attachments;
}

我还有一个用于Post请求的RestController

@PostMapping()
public Flux<FileUpload> saveFile(@RequestBody FileUpload fileUpload) {
    return this.fileUploadService.create(fileUpload);
}

然后我通过Postman中的requestbody传递这个Json

[
    {
        "filename": "test.pdf",
        "task_id": 2,
        "e_tag": 1234567890
    },
    {
        "filename": "test2.pdf",
        "task_id": 2,
        "e_tag": 0987654321
    }
]

我的问题是如何迭代Flux然后将数据保存到数据库
英文:

I'm new to Spring WebFlux and I am trying to insert multiple rows to DB.

I'm creating a REST API for inserting data to DB.

I have a service for saving Flux object.

public Flux&lt;FileUpload&gt; create(FileUpload fileUpload) {
       Flux&lt;FileUpload&gt; attachments = Flux.just(fileUpload)
               .map(upload -&gt; {
                   new FileUpload(upload);
                   this.fileUploadRepository.save(upload);

                   return upload;
               });

       return attachments;
}

And I have a RestController for Post request.

@PostMapping()
    public Flux&lt;FileUpload&gt; saveFile(@RequestBody FileUpload fileUpload) {
        return this.fileUploadService.create(fileUpload);
    }

Then I am passing this Json via requestbody in Postman

[
    {
        &quot;filename&quot;: &quot;test.pdf&quot;,
        &quot;task_id&quot;: 2,
        &quot;e_tag&quot;: 1234567890
    },
    {
        &quot;filename&quot;: &quot;test2.pdf&quot;,
        &quot;task_id&quot;: 2,
        &quot;e_tag&quot;: 0987654321
    }
]

My question is how to iterate over flux then save the data to the database.

答案1

得分: 1

如果您正在使用Spring Data,那么ReactiveCrudRepository会暴露一个方法,该方法接受一个Flux作为参数,并将所有内容保存到数据库中。

&lt;S extends T&gt; Flux&lt;S&gt; saveAll(Publisher&lt;S&gt; entityStream);

如果您未使用Spring Data,请告知我,我将更新此回答。

英文:

If you are using spring data, then the ReactiveCrudRepository exposes a method which accepts a Flux as an argument and saves all to the db.

&lt;S extends T&gt; Flux&lt;S&gt; saveAll(Publisher&lt;S&gt; entityStream);

Please let me know if you are not using spring data and I will update this answer.

huangapple
  • 本文由 发表于 2020年9月10日 17:02:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/63826317.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定