2016-05-03 51 views
2

我的情況: 我有一個組織可以有很多工人。我試圖在SDR項目的主要貢獻作者this example之後向組織添加新工作人員,並且我收到各種錯誤(包括204但沒有任何反應)。使用spring-data-rest將資源添加到集合

這裏是我的實體和休息電話:

@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; 
} 

GET 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() - >組織

isInstance(豆) - > org.springframework.hateoas.Resource

的bean實例

上的任何輸入這個?我遵循了這封信的指示。

回答

1

下面是答案(它走出去散步,清理我的頭,打這個)。

你必須張貼到協會資源

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

這發生在我身上金塊,然後我去了,重讀後。

對於像我這樣的愚蠢錯誤,400錯誤會更有用。

+0

This Works。我處於類似的情況。但是,這不斷更新(僅)一個資源。你知道如何添加新資源嗎?例如,向組織添加多個工作人員。 – lealceldeiro

+0

你不能 - 這不是它的工作原理。要添加一個額外的資源,你需要'GET/hal/organizations/1/workers'產生一個你添加到的數組,然後'PUT'或'POST'到同一個資源。我認爲'PATCH'在語義上將是正確的一步,但我知道一個事實,即PATCH支持與其他動詞相同的方式。 –