Spring HATEOAS在响应中更改实体名称

问题描述

我的API网址是:http://127.0.0.1:8080/api/discussions/

它返回以下内容

{
    "_embedded": {
        "discussionModels": [
            {
                "id": "9f3f3857-84e1-4e2b-a476-759ac82c1e9f","title": "Example title 1","_links": {
                    "discussions": {
                        "href": "http://127.0.0.1:8080/api/discussions/"
                    }
                }
            },{
                "id": "32e16f18-2f44-4e75-81e4-b9c60d980752","title": "Example title 2",{
                "id": "9671a0e5-56de-48fd-9ef0-ac6d883500d2","title": "Example title 3","_links": {
                    "discussions": {
                        "href": "http://127.0.0.1:8080/api/discussions/"
                    }
                }
            }
        ]
    },"_links": {
        "self": {
            "href": "http://127.0.0.1:8080/api/discussions/"
        }
    }

}

我试图通过在域对象上使用@Relation注释将“ discussionModels”名称更改为“ discussions”:

discussionModel

import org.springframework.hateoas.RepresentationModel;
import org.springframework.hateoas.server.core.Relation;

import javax.persistence.*;
import java.util.UUID;

@Entity
@Table(name="discussion")
@Relation(collectionRelation = "discussions",itemRelation = "discussion")
public class discussionModel extends RepresentationModel<discussionModel> {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    public UUID id;
    private String title;

    public discussionModel() { }

    public discussionModel(String title) {
        this.title = title;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public UUID getId() {
        return id;
    }

    public void setId(UUID id) {
        this.id = id;
    }
}

但是没有效果

我的控制器如下:

    @GetMapping("/")
CollectionModel<EntityModel<discussionModel>> all() {
    List<EntityModel<discussionModel>> discussions =
            discussionService.all()
                .map(assembler::toModel)
                .collect(Collectors.toList());

    return CollectionModel.of(
            discussions,linkTo(methodon(discussionController.class).all()).withSelfRel()
    );
}

我的汇编代码

@Component
public class discussionModelAssembler
        implements RepresentationModelAssembler<
            discussionModel,EntityModel<discussionModel>> {

    @Override
    public EntityModel<discussionModel> toModel(discussionModel discussionModel) {
        return EntityModel.of(
                discussionModel,//                linkTo(methodon(discussionController.class)).withSelfRel(),linkTo(methodon(discussionController.class).all()).withRel("discussions")
        );
    }
}

我期望的行为是@Relation批注有效,但仍向我显示discussionModels”。

我有一个测试用例,位于:https://github.com/dlynch158/relationtest

显示出相同的行为。

谢谢。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)