Java 如何使用 Spring RestTemplate 使用 Page<Entity> 响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34099559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:18:48  来源:igfitidea点击:

How to consume Page<Entity> response using Spring RestTemplate

javaspringrestspring-dataspring-data-rest

提问by bgalek

I'm using spring data (mongoDb) and I've got my repository:

我正在使用 spring 数据(mongoDb)并且我有我的存储库:

public interface StoriesRepository extends PagingAndSortingRepository<Story, String> {}

Then i have a controller:

然后我有一个控制器:

@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<Page<StoryResponse>> getStories(Pageable pageable) {
    Page<StoryResponse> stories = storiesRepository.findAll(pageable).map(StoryResponseMapper::toStoryResponse);
    return ResponseEntity.ok(stories);
}

Everything works fine, but I can't consume my endpoint using RestTemplate getForEntity method:

一切正常,但我无法使用 RestTemplate getForEntity 方法使用我的端点:

def entity = restTemplate.getForEntity(getLocalhost("/story"), new TypeReference<Page<StoryResponse>>(){}.class)

What class should I provide to successfully deserialize my Page of entities?

我应该提供什么类来成功反序列化我的实体页面?

采纳答案by Ali Dehghani

new TypeReference<Page<StoryResponse>>() {}

The problem with this statement is that Hymanson cannot instantiate an abstract type. You should give Hymanson the information on how to instantiate Pagewith a concrete type. But its concrete type, PageImpl, has no default constructor or any @JsonCreators for that matter, so you can notuse the following code either:

此语句的问题在于 Hymanson 无法实例化抽象类型。您应该向 Hymanson 提供有关如何Page使用具体类型实例化的信息。但是它的具体类型 ,PageImpl没有默认构造函数或任何@JsonCreators ,因此您也不能使用以下代码:

new TypeReference<PageImpl<StoryResponse>>() {}

Since you can't add the required information to the Pageclass, It's better to create a custom implementation for Pageinterface which has a default no-arg constructor, as in this answer. Then use that custom implementation in type reference, like following:

由于您无法向Page类添加所需的信息,因此最好为Page具有默认无参数构造函数的接口创建自定义实现,如本答案所示。然后在类型引用中使用该自定义实现,如下所示:

new TypeReference<CustomPageImpl<StoryResponse>>() {}

Here are the custom implementation, copied from linked question:

以下是从链接问题复制的自定义实现:

public class CustomPageImpl<T> extends PageImpl<T> {
    private static final long serialVersionUID = 1L;
    private int number;
    private int size;
    private int totalPages;
    private int numberOfElements;
    private long totalElements;
    private boolean previousPage;
    private boolean firstPage;
    private boolean nextPage;
    private boolean lastPage;
    private List<T> content;
    private Sort sort;

    public CustomPageImpl() {
        super(new ArrayList<>());
    }

    @Override
    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    @Override
    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    @Override
    public int getTotalPages() {
        return totalPages;
    }

    public void setTotalPages(int totalPages) {
        this.totalPages = totalPages;
    }

    @Override
    public int getNumberOfElements() {
        return numberOfElements;
    }

    public void setNumberOfElements(int numberOfElements) {
        this.numberOfElements = numberOfElements;
    }

    @Override
    public long getTotalElements() {
        return totalElements;
    }

    public void setTotalElements(long totalElements) {
        this.totalElements = totalElements;
    }

    public boolean isPreviousPage() {
        return previousPage;
    }

    public void setPreviousPage(boolean previousPage) {
        this.previousPage = previousPage;
    }

    public boolean isFirstPage() {
        return firstPage;
    }

    public void setFirstPage(boolean firstPage) {
        this.firstPage = firstPage;
    }

    public boolean isNextPage() {
        return nextPage;
    }

    public void setNextPage(boolean nextPage) {
        this.nextPage = nextPage;
    }

    public boolean isLastPage() {
        return lastPage;
    }

    public void setLastPage(boolean lastPage) {
        this.lastPage = lastPage;
    }

    @Override
    public List<T> getContent() {
        return content;
    }

    public void setContent(List<T> content) {
        this.content = content;
    }

    @Override
    public Sort getSort() {
        return sort;
    }

    public void setSort(Sort sort) {
        this.sort = sort;
    }

    public Page<T> pageImpl() {
        return new PageImpl<>(getContent(), new PageRequest(getNumber(),
                getSize(), getSort()), getTotalElements());
    }
}

回答by pathfinder

You can probably use exchange method of restTemplate and get the body from it..

您可能可以使用 restTemplate 的交换方法并从中获取正文..

Check the following answer https://stackoverflow.com/a/31947188/3800576. This might help you

检查以下答案https://stackoverflow.com/a/31947188/3800576。这可能会帮助你

回答by jtcotton63

I know this thread is a little old, but hopefully someone will benefit from this.

我知道这个线程有点旧,但希望有人能从中受益。

@Ali Dehghani's answer is good, except that it re-implements what PageImpl<T>has already done. I considered this to be rather needless. I found a better solution by creating a class that extends PageImpl<T>and specifies a @JsonCreatorconstructor:

@Ali Dehghani 的回答很好,只是它重新实现了PageImpl<T>已经完成的工作。我认为这是相当没有必要的。我通过创建一个扩展PageImpl<T>并指定@JsonCreator构造函数的类找到了一个更好的解决方案:

import com.fasterxml.Hymanson.annotation.JsonCreator;
import com.fasterxml.Hymanson.annotation.JsonProperty;
import com.company.model.HelperModel;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import java.util.List;

public class HelperPage extends PageImpl<HelperModel> {

    @JsonCreator
    // Note: I don't need a sort, so I'm not including one here.
    // It shouldn't be too hard to add it in tho.
    public HelperPage(@JsonProperty("content") List<HelperModel> content,
                      @JsonProperty("number") int number,
                      @JsonProperty("size") int size,
                      @JsonProperty("totalElements") Long totalElements) {
        super(content, new PageRequest(number, size), totalElements);
    }
}

Then:

然后:

HelperPage page = restTemplate.getForObject(url, HelperPage.class);

This is the same as creating a CustomPageImpl<T>class but allows us to take advantage of all the code that's already in PageImpl<T>.

这与创建CustomPageImpl<T>类相同,但允许我们利用PageImpl<T>.

回答by Vladimir Mitev

As "pathfinder" mentioned you can use exchangemethod of RestTemplate. However instead of passing ParameterizedTypeReference<Page<StoryResponse>>()you should pass ParameterizedTypeReference<PagedResources<StoryResponse>>(). When you get the response you could retrieve the content - Collection<StoryResponse>.

作为“探路者”中提到,您可以使用exchange的方法RestTemplate。但是,ParameterizedTypeReference<Page<StoryResponse>>()您应该通过而不是通过ParameterizedTypeReference<PagedResources<StoryResponse>>()。当您收到响应时,您可以检索内容 - Collection<StoryResponse>

The code should look like this:

代码应如下所示:

ResponseEntity<PagedResources<StoryResponse>> response = restTemplate.exchange(getLocalhost("/story"),
        HttpMethod.GET, null, new ParameterizedTypeReference<PagedResources<StoryResponse>>() {});
PagedResources<StoryResponse> storiesResources = response.getBody();
Collection<StoryResponse> stories = storiesResources.getContent();

Apart from the content storiesResourcesholds page metadata and links too.

除了内容也storiesResources包含页面元数据和链接。

A more step-by-step explanation is available here: https://stackoverflow.com/a/46847429/8805916

此处提供了更多分步说明:https: //stackoverflow.com/a/46847429/8805916

回答by pama

I can only make it work downgrading Spring library to 1.* and not using 2.* I had to create my own code for the Page which does not extends PageImpl

我只能使它工作将 Spring 库降级到 1.* 而不是使用 2.* 我必须为不扩展 PageImpl 的页面创建自己的代码

回答by Terrence Wei

If you looking at this thread, and if you try this answer https://stackoverflow.com/a/44895867/8268335

如果您查看此线程,并且尝试此答案 https://stackoverflow.com/a/44895867/8268335

You will meet the 2nd problem:

你会遇到第二个问题:

Can not construct instance of org.springframework.data.domain.Pageable

Then I find the perfect solution from here: https://stackoverflow.com/a/42002709/8268335

然后我从这里找到了完美的解决方案:https: //stackoverflow.com/a/42002709/8268335

I create the class RestPageImplfrom the answer above and problem solved.

我根据RestPageImpl上面的答案创建了类并解决了问题。