使用spring-data-rest将资源添加到集合

时间:2016-05-03 02:11:13

标签: spring-data spring-data-jpa spring-data-rest

我的情况: 我有一个可以有很多工人的组织。我正在尝试在SDR项目的主要撰稿人this example之后向组织添加一名新工作人员并且我得到了各种错误(包括204但没有任何反应)。

以下是我的实体和休息电话:

@Entity
public class Organization {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;


    @OneToMany
    @JoinTable(name = "OrganizationWorker", joinColumns = {@JoinColumn(name = "OrganizationID")},
            inverseJoinColumns = {@JoinColumn(name = "WorkerID")})
    private Set<Worker> workers = new LinkedHashSet<>();
}

public class Worker {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    @NotNull
    private String givenName;

    @NotNull
    private String familyName;

    @NotNull
    private LocalDate dob;

    @NotNull
    private String nationalId;

    private byte[] photo;
}

获取http://localhost:8080/hal

{
    "_links": {

        "workers": {
            "href": "http://localhost:8080/hal/workers{?page,size,sort}",
            "templated": true
        }
    }
}

POST http://localhost:8080/hal/workers

{
 "givenName": "James",
    "familyName": "Bond",
    "dob": "1970-01-01",
    "nationalId": "XXX-60-XXXX",
    "photo": null,
}

响应:

Location: http://localhost:8080/hal/workers/8
Date: Mon, 02 May 2016 16:53:02 GMT
Server: Apache-Coyote/1.1
Transfer-Encoding: chunked
X-Application-Context: application
Content-Type: application/hal+json;charset=UTF-8


{
    "givenName": "James",
    "familyName": "Bond",
    "dob": "1970-01-01",
    "nationalId": "XXX-60-XXXX",
    "photo": null,
    "_links": {
        "self": {
            "href": "http://localhost:8080/hal/workers/8"
        },
        "worker": {
            "href": "http://localhost:8080/hal/workers/8"
        }
    }
}

最后一步,根据说明中的链接:

curl -X PUT -H "ContentType: text/uri-list" http://localhost:8080/hal/organizations/2 -d 'http://localhost:8080/hal/workers/8'

{
    "cause": null,
    "message": "Target bean is not of type of the persistent entity!"
}

进行一些调试很明显具体的投诉是什么。堆栈跟踪在这里引出:

@Override
public PersistentPropertyAccessor getPropertyAccessor(Object bean) {

    Assert.notNull(bean, "Target bean must not be null!");
    Assert.isTrue(getType().isInstance(bean), "Target bean is not of type of the persistent entity!");

    return new BeanWrapper<Object>(bean);
}
  

getType() - &gt;组织

     

isInstance(bean) - &gt; org.springframework.hateoas.Resource的bean实例

对此有任何意见吗?我按照说明写了这封信。

1 个答案:

答案 0 :(得分:1)

这是答案(走出去散步以清除头部然后点击它)。

您必须发布到关联资源

  

http://localhost:8080/hal/organizations/1/

那个金块发生在我身上然后我重新阅读了这篇文章。

对于像我这样的愚蠢错误,400错误本来会更有用。