我對Spring Data Rest的第一個實驗失敗了。我採取了「入門」並對其進行了一些修改,以創建兩個具有多對一關係的實體。這些實體是Book
和Shelve
,許多書籍可以共享一個擱置。404關於設置關聯資源
的Shelve
實體看起來是這樣的:
package hello;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Shelve
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private int length;
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
}
的Book
是指它:
package hello;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
@Entity
public class Book
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String title;
@ManyToOne
private Shelve shelve;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Shelve getShelve() {
return shelve;
}
public void setShelve(Shelve shelve) {
this.shelve = shelve;
}
}
整個項目可here in GitHub。
現在,我可以添加一個擱置:
curl -i -X POST -H "Content-Type:application/json" -d "{ \"length\" : \"30\" }" http://localhost:8080/shelves
HTTP/1.1 201
Location: http://localhost:8080/shelves/1
Content-Type: application/hal+json;charset=UTF-8
Transfer-Encoding: chunked
Date: Thu, 17 Nov 2016 16:05:02 GMT
{
"length" : 30,
"_links" : {
"self" : {
"href" : "http://localhost:8080/shelves/1"
},
"shelve" : {
"href" : "http://localhost:8080/shelves/1"
}
}
}
然後一本書:
curl -i -X POST -H "Content-Type:application/json" -d "{ \"title\" : \"The Battle of Life\" }" http://localhost:8080/books
HTTP/1.1 201
Location: http://localhost:8080/books/1
Content-Type: application/hal+json;charset=UTF-8
Transfer-Encoding: chunked
Date: Thu, 17 Nov 2016 16:05:02 GMT
{
"title" : "The Battle of Life",
"_links" : {
"self" : {
"href" : "http://localhost:8080/books/1"
},
"book" : {
"href" : "http://localhost:8080/books/1"
},
"shelve" : {
"href" : "http://localhost:8080/books/1/shelve"
}
}
}
然後我嘗試把書放在貨架,但失敗:
curl -i -X PUT -H "ContentType: text/uri-list" -d "http://localhost:8080/shelves/1" http://localhost:8080/books/1/shelve
HTTP/1.1 404
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Thu, 17 Nov 2016 16:05:02 GMT
{"timestamp":1479398702523,"status":404,"error":"Not Found","message":"No message available","path":"/books/1/shelve"}
任何想法這裏有什麼問題嗎?
這可能會起作用,但那不是我想要的模型。上面的代碼顯然只是探索Spring Data Rest。我需要一個ManyToOne。 – Bert
@伯特你加了@ onetomany otherside部分並嘗試了ManyToOne的補充? – kuhajeyan
不,我沒有那樣做,因爲我不想在我的模型中有這個。我需要一種單向可導航的關係。 – Bert